我需要在string
中找到所有大写字母。例如
输入:Electronics and Communication Engineering
输出:ECE
答案 0 :(得分:5)
如果你坚持正则表达式:
string source = @"Electronics and Communication Engineering";
string result = string.Concat(Regex
.Matches(source, "[A-Z]")
.OfType<Match>()
.Select(match => match.Value));
Linq 是一个(更短的)替代方案:
string result = string.Concat(source.Where(c => c >= 'A' && c <= 'Z'));
答案 1 :(得分:2)
使用LINQ:
string text = "Electronics and Communication Engineering";
var capitalLetters = text.Where(c => char.IsUpper(c)).ToArray();
答案 2 :(得分:2)
Linq解决方案Example is here:
扩展方法Where
将帮助您从给定字符串中获取大写字母。您可以使用String.Join
或String.Concat
(更好,如 DmitryBychenko 所示)来获得最终输出为字符串。浏览以下代码段
string inputStr = "Electronics and Communication Engineering";
string outputStr=String.Concat(inputStr.Where(x=>Char.IsUpper(x)));
Console.WriteLine(outputStr);
答案 3 :(得分:0)
var s = "Electronics and Communication Engineering";
result = string.Concat(s.Select(c => char.IsUpper(c) ? c.ToString() : ""))
.TrimStart();