【问题标题】:Get String (Text) before next upper letter在下一个大写字母之前获取字符串(文本)
【发布时间】:2012-07-02 14:25:14
【问题描述】:

我有以下几点:

string test = "CustomerNumber";

string test2 = "CustomerNumberHello";

结果应该是:

string result = "Customer";

字符串中的第一个单词是结果,第一个单词一直到第一个大写字母,这里是'N'

我已经尝试过这样的一些事情:

var result = string.Concat(s.Select(c => char.IsUpper(c) ? " " + c.ToString() : c.ToString()))
    .TrimStart();

但没有成功,希望有人可以为我提供一个小而干净的解决方案(没有 RegEx)。

【问题讨论】:

  • 你不能使用正则表达式有什么原因吗?这就是它存在的原因。
  • 我的应用程序中有一些其他的字符串操作,它们都没有正则表达式。试图保持一些顺序。但如果没有其他方法,我也会使用正则表达式。。

标签: c# .net string linq


【解决方案1】:

以下应该有效:

var result = new string(
    test.TakeWhile((c, index) => index == 0 || char.IsLower(c)).ToArray());

【讨论】:

  • @abatishchev:是的,但是在您需要将它注入 在结果字符串的前面 之后才能正确输出。 this 方式更优雅imo-
【解决方案2】:

您可以通过字符串查看哪些值 (ASCII) 低于 97 并删除结尾。不是最漂亮或 LINQiest 的方式,但它确实有效......

    string test2 = "CustomerNumberHello";

    for (int i = 1; i < test2.Length; i++)
    {
        if (test2[i] < 97)
        {
            test2 = test2.Remove(i, test2.Length - i);
            break;
        }
    }
    Console.WriteLine(test2); // Prints Customer

【讨论】:

    【解决方案3】:

    试试这个

     private static string GetFirstWord(string source)
            {
                return source.Substring(0, source.IndexOfAny("ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToArray(), 1));
            }
    

    【讨论】:

      【解决方案4】:

      Z][a-z]+ 正则表达式它将字符串拆分为以大字母开头的字符串她就是一个例子

        regex = "[A-Z][a-z]+";
                  MatchCollection mc = Regex.Matches(richTextBox1.Text, regex);
                  foreach (Match match in mc)
                      if (!match.ToString().Equals(""))
                          Console.writln(match.ToString() + "\n");
      

      【讨论】:

      • 来自 OP 的帖子hope someone could offer me a small and clean solution (without RegEx).
      【解决方案5】:

      我已经测试过了,这行得通:

      string cust = "CustomerNumberHello";
      string[] str = System.Text.RegularExpressions.Regex.Split(cust, @"[a-z]+");
      string str2 = cust.Remove(cust.IndexOf(str[1], 1));
      

      【讨论】:

      • 好吧,解释一下为什么这被否决的原因会很有用。
      • OP 专门要求没有正则表达式的答案。
      • 好吧,这被忽视了。我的错。
      猜你喜欢
      • 2022-07-02
      • 2021-09-12
      • 1970-01-01
      • 2017-08-31
      • 2023-02-23
      • 1970-01-01
      • 2016-10-16
      • 1970-01-01
      • 2017-09-05
      相关资源
      最近更新 更多