获取下一个大写字母之前的字符串(文本)

3

我有以下内容:

string test = "CustomerNumber";

或者
string test2 = "CustomerNumberHello";

the result should be:

string result = "Customer";

从字符串中取得的第一个单词是结果,该单词一直延伸到第一个大写字母,例如这里的 'N'

我已经尝试过以下方法:

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

但是一直没有成功,希望有人可以给我提供一个小而简洁的解决方案(不使用正则表达式)。

你不能使用正则表达式吗?它的存在就是为了解决这类问题。 - Jason Down
1
我在我的应用程序中有一些其他的字符串操作,它们都没有使用正则表达式。试图保持一些秩序。但如果没有其他办法,我也会使用正则表达式。 - eMi
5个回答

10

以下代码应该可以正常工作:

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

@abatishchev:是的,但是之后你需要将它插入到结果字符串的前面以获得正确的输出。用这种方式更加优雅 在我看来- - Tigran

1

你可以遍历字符串,查看哪些值(ASCII)低于97,并删除末尾。这不是最漂亮或最LINQ的方法,但它有效...

    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

1

试试这个

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

-3

使用 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");

3
原文:From OP's post hope someone could offer me a small and clean solution (without RegEx). 翻译:来自发帖者的帖子:“希望有人能够提供一个小而干净的解决方案(不使用正则表达式)。”。 - dtsg

-3

我已经测试过,这是可行的:

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

提供一下为什么这个被踩的解释会很有用。 - Shakti Prakash Singh
1
OP特别要求不使用正则表达式来回答。 - NominSim
好吧,那没被注意到。我的错。 - Shakti Prakash Singh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接