How to check/filter uppercase words alone from a string using C#?
How to check/filter uppercase words alone from a string using C#? I don't want to use "Char.IsUpper()" by looping through each letter of a word for checking Upper case for th开发者_C百科e same. Is there any way very simple code to accomplish this task? with LINQ etc.?
What about this?
string test = "This IS a STRING";
var upperCaseWords = test.Split(' ').Where( w => w == w.ToUpper());
upperCaseWords now contain all upper case words in the string.
Using ordinal string comparison makes the comparison faster: unicode, byte per byte without of culture-specific checks.
// the TEST string
var result = input
.Split(' ')
.Where(w => String.Equals(w, w.ToUpper(), StringComparison.Ordinal));
// TEST
You could use a Regex:
using System.Text.RegularExpressions;
string input = "hello hi HELLO hi HI";
MatchCollection matches = Regex.Matches(" " + input + " ", @" [A-Z]* ");
foreach (Match m in matches)
{
MessageBox.Show(m.Value);
}
Edit: To handle the case where the first/last word is all caps, you could just add a space to each side of the input string. I've updated the example above.
Do you mean: String.ToUpper() ?
Edit: Ok, sorry I misunderstood the question.
You can do it using Regex: http://oreilly.com/windows/archive/csharp-regular-expressions.html
Find all words where initial letter is uppercase
string t17 = "This is A Test of Initial Caps";
string p17 = @"(\b[^\Wa-z0-9_][^\WA-Z0-9_]*\b)";
MatchCollection mc17 = Regex.Matches(t17, p17);
Finding All Caps Words
string t15 = "This IS a Test OF ALL Caps";
string p15 = @"(\b[^\Wa-z0-9_]+\b)";
MatchCollection mc15 = Regex.Matches(t15, p15);
You want just uppercase words from a string, huh?
Maybe something like this?
var upperCaseWords = from w in Regex.Split(text, @"\s+")
where char.IsUpper(w[0])
select w;
If you want words that are in ALL uppercase letters (like THIS), you can use basically the same approach, only with a different predicate:
var upperCaseWords = from w in Regex.Split(text, @"\s+")
where w.All(c => char.IsUpper(c))
select w;
精彩评论