[英]How many specified chars are in a string?
取一個字符串例如,作為550e8400-e29b-41d4-a716-446655440000
一個怎么能算多少 -
字符是在這樣的字符串?
我目前正在使用:
int total = "550e8400-e29b-41d4-a716-446655440000".Split('-').Length + 1;
是否有任何我們不需要加1的方法……例如使用Count
?
所有其他方法,例如
Contains
IndexOf
等只返回第一位置和boolean
值,沒有什么回報有多少被發現。
我想念什么?
為此,可以使用LINQ方法Enumerable.Count
(請注意, string
是IEnumerable<char>
):
int numberOfHyphens = text.Count(c => c == '-');
參數是Func<char, bool>
,這是一個謂詞,用於指定何時將某個項目視為已“通過”過濾器。
這(寬松地說)等效於:
int numberOfHyphens = 0;
foreach (char c in text)
{
if (c == '-') numberOfHyphens++;
}
using System.Linq;
..
int total = "550e8400-e29b-41d4-a716-446655440000".Count(c => c == '-');
int total = "550e8400-e29b-41d4-a716-446655440000".Count(c => c == '-');
最直接的方法是簡單地遍歷字符,因為這是任何一種算法都必須采取的某種方法:
int total = 0;
foreach (char c in theString) {
if (c == '-') total++;
}
您可以使用擴展方法執行基本相同的操作:
int total = theString.Count(c => c == '-');
要么:
int total = theString.Aggregate(0, (t,c) => c == '-' ? t + 1 : t)
然后有一些有趣的技巧(但效率較低),例如刪除字符並比較長度:
int total = theString.Length - theString.Replace("-", String.Empty).Length;
或使用正則表達式查找字符的所有出現:
int total = Regex.Matches(theString, "-").Count;
int total = "550e8400-e29b-41d4-a716-446655440000".Count(c => c == '-')
要查找字符串中的“-”號,您將需要遍歷字符串並檢查每個字符,因此最簡單的方法是編寫一個執行該操作的函數。 使用Split實際上會花費更多時間,因為它無緣無故地創建了數組。
另外,它使您想做的事情變得混亂,甚至看起來您弄錯了(您需要減去1)。
嘗試這個:
string s = "550e8400-e29b-41d4-a716-446655440000";
int result = s.ToCharArray().Count( c => c == '-');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.