簡體   English   中英

C#:如何僅從字符串中返回第一組大寫字母單詞?

[英]C#: How can I only return the first set of capital letter words from a string?

如果我想解析一個字符串,僅返回其中的所有大寫字母,我該怎么做?

例:

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

我只想返回"OTHER COMMENTS"

  • 這些第一個大寫單詞可能很多,確切的數目未知。
  • 字符串中可能有其他單詞,但我只想忽略所有大寫字母。

您可以組合使用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()));

您可以將字符串作為字符數組循環遍歷。 要檢查char是否為大寫,請使用Char.IsUpper https://www.dotnetperls.com/char-islower 因此,在循環中您可以說它是否為字符-設置一個標志,我們開始讀取該標志。 然后將該字符添加到字符集合中。 繼續循環,一旦它不再是大寫char並且該標志仍然為true,就退出循環。 然后將char的集合作為字符串返回。

希望能有所幫助。

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

將其拆分為單詞,然后在單詞的大寫形式與單詞相同的情況下接受單詞。 然后將它們與空格分隔符組合在一起。

您也可以使用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]);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM