如何从字符串的末尾开始子字符串

本文关键字:字符串 开始 | 更新日期: 2023-09-27 18:15:11

我想截断字符串的末尾:

输入字符串

/O=Shore Tel/OU=CANDY/cn=Recipients/cn=PAgricola
/O=Shore Tel/OU=CANDY/cn=Recipients/cn=YAchmanov
/o=Shore Tel/ou=Exchange Administrative Group (FYDIBOHF23SPDLT)/cn=Recipients/cn=Mukul Agrawal2f2
/o=Shore Tel/ou=Exchange Administrative Group (FYDIBOHF23SPDLT)/cn=Recipients/cn=Nick Aiello816

输出字符串:

/O=Shore Tel/OU=CANDY/cn=Recipients
/O=Shore Tel/OU=CANDY/cn=Recipients
/o=Shore Tel/ou=Exchange Administrative Group (FYDIBOHF23SPDLT)/cn=Recipients
/o=Shore Tel/ou=Exchange Administrative Group (FYDIBOHF23SPDLT)/cn=Recipients
你能给我一个建议吗?

如何从字符串的末尾开始子字符串

看起来您可以找到"/cn="的最后一个索引,以及从0到该位置的子字符串:

int pos = str.LastIndexOf("/cn=");
if (pos > 0) {
    str = str.Substring(0, pos);
}

演示。

在LINQ中只有一行

string input = @"/O=Shore Tel/OU=CANDY/cn=Recipients/cn=PAgricola
                 /O=Shore Tel/OU=CANDY/cn=Recipients/cn=YAchmanov
                 /o=Shore Tel/ou=Exchange Administrative Group (FYDIBOHF23SPDLT)/cn=Recipients/cn=Mukul Agrawal2f2
                 /o=Shore Tel/ou=Exchange Administrative Group (FYDIBOHF23SPDLT)/cn=Recipients/cn=Nick Aiello816";
var result = string.Join("'n", input.Split(''n')
                                    .Select(x => x.Substring(0, x.LastIndexOf('/')))
                                    .ToArray());
Console.WriteLine(result);

为了可读性,我使用了逐字的@字符并对齐了子字符串,但这引入了一些不必要的空白。您的输入字符串是如何格式化的并不清楚,但这里的关键点是设置结果变量的那一行。

    string s = "/O=Shore Tel/OU=CANDY/cn=Recipients/cn=PAgricola";
    s=s.Substring(0, s.IndexOf("s/cn="));