如果我想解析一个字符串以仅返回其中的所有大写字母,我该怎么做?
示例:
"OTHER COMMENTS These are other comments that would be here. Some more
comments"
我只想返回"OTHER COMMENTS"
答案 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]);
}