C#:如何仅从字符串中返回第一组大写字母单词?

时间:2018-11-02 20:40:53

标签: c# parsing

如果我想解析一个字符串以仅返回其中的所有大写字母,我该怎么做?

示例:

"OTHER COMMENTS These are other comments that would be here. Some more
comments"

我只想返回"OTHER COMMENTS"

  • 这些第一个大写单词可以很多,准确的计数是 未知。
  • 所有大写字母后面的字符串中可能还有其他单词 我只想忽略的东西。

4 个答案:

答案 0 :(得分:6)

您可以使用Split(将句子分解为单词),SkipWhile(跳过并非全部大写的单词),ToUpper(测试单词)的组合反对它的大写字母)和TakeWhile(一旦找到一个,则取所有连续的大写单词)。最后,可以使用Join重新连接这些单词:

string words = "OTHER COMMENTS These are other comments that would be here. " + 
    "Some more comments";

string capitalWords = string.Join(" ", words
    .Split()
    .SkipWhile(word => word != word.ToUpper())
    .TakeWhile(word => word == word.ToUpper()));

答案 1 :(得分:0)

您可以将字符串作为字符数组循环遍历。要检查字符是否为大写,请使用Char.IsUpper https://www.dotnetperls.com/char-islower。因此,在循环中您可以说它是否为字符-设置一个标志,我们开始读取该标志。然后将该字符添加到字符集合中。继续循环,一旦它不再是大写char并且该标志仍然为true,就退出循环。然后将char的集合作为字符串返回。

希望有帮助。

答案 2 :(得分:0)

var input = "OTHER COMMENTS These are other comments that would be here. Some more comments";
var output = String.Join(" ", input.Split(' ').TakeWhile(w => w.ToUpper() == w));

将其拆分为单词,然后在单词的大写形式与单词相同的情况下接受单词。然后将它们与空格分隔符组合在一起。

答案 3 :(得分:0)

您也可以使用Regex

using System.Text.RegularExpressions;
...
// The Regex pattern is any number of capitalized letter followed by a non-word character.
// You may have to adjust this a bit.
Regex r = new Regex(@"([A-Z]+\W)+"); 
string s = "OTHER COMMENTS These are other comments that would be here. Some more comments";
MatchCollection m = r.Matches(s);
// Only return the first match if there are any matches.
if (m.Count > 0)
{
    Console.WriteLine(r.Matches(s)[0]);
}