【问题标题】:How to substring a string from the end of the string [duplicate]如何从字符串的末尾子串一个字符串[重复]
【发布时间】:2014-09-18 04:01:52
【问题描述】:

我想剪掉sring的结尾:

输入字符串:

/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

你能给我一些建议吗?

【问题讨论】:

  • 搜索关于 String.Split、String.LastIndexOf、String.Substring。这就是解决难题所需的全部知识。
  • 我的问题和题目不同。我看到了

标签: c# string winforms substring substr


【解决方案1】:
    string s = "/O=Shore Tel/OU=CANDY/cn=Recipients/cn=PAgricola";
    s=s.Substring(0, s.IndexOf("s/cn="));

【讨论】:

  • 这将在第一次出现 /cn= 时切断字符串,这不是所要求的。
  • @steve:查看更新
【解决方案2】:

在 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);

为了便于阅读,我使用了逐字的 @ 字符并对齐了子字符串,但这会引入一些不需要的空格。目前尚不清楚您的输入字符串是如何格式化的,但这里的关键点是设置结果变量的行。

【讨论】:

    【解决方案3】:

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

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

    Demo.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-05
      • 1970-01-01
      • 1970-01-01
      • 2012-10-04
      • 2019-09-26
      相关资源
      最近更新 更多