2012-07-05 74 views
-5

字符串中的週期數:我如何才能知道我有一個字符串,如與C#

1.1 
1.11 
11.11 
1.1.1 
11.11.11 

所有這些都是單一字符串,沒有空格,只有數字和句點。

我需要能夠計算字符串中的句點數。有沒有簡單的方法在C#中做到這一點?

+12

所以,通常的問題:你嘗試過什麼(http://mattgemmell.com/2008/12/08/what-have - 你試了/)?有兩種可能性:1)沒有=>你的問題被關閉,2)你已經嘗試了某些東西,在這種情況下,你更新你的問題來顯示你的努力並解釋你遇到的困難。現在有兩種可能性:2.1)你的描述很清楚,你會得到一個答案,2.2)你的描述不好,在這種情況下你可能會被要求澄清。這就是Stack Overflow的工作方式,以便您能夠提出問題。 – 2012-07-05 17:05:26

+5

來吧,現在。你不能在谷歌搜索中投擲磚塊,而不會有十幾個結果回答這個問題。 – 2012-07-05 17:06:09

+1

這是功課嗎? – 2012-07-05 17:06:56

回答

11

有多種方法,例如(需要框架3.5或更高版本):

int cnt = str.Count(c => c == '.'); 

或:

int cnt = 0; 
foreach (char c in str) if (c == '.') cnt++; 

或:

int cnt = str.Length - str.Replace(".", "").Length; 
+4

當然,最快的是一個普通的ol'' for循環。不過,我認爲字符串替換法是邪惡天才的作品。 – 2012-07-05 17:11:19

+0

對於多種方法而言+1爲術語邪惡天才 – Tilak 2012-07-05 17:13:11

+0

+1。替換很有趣。 – Tyrsius 2012-07-05 17:14:07

5

對谷歌第一個結果,當我輸入你的確切問題....

http://social.msdn.microsoft.com/Forums/en/csharplanguage/thread/4be305bf-0b0a-4f6b-9ad5-309efa9188b8

做一些研究...

int count = 0; 
string st = "Hi, these pretzels are making me thirsty; drink this tea. Run like heck. It's a good day."; 
foreach(char c in st) { 
    if(char.IsLetter(c)) { 
    count++; 
    } 
} 
lblResult.Text = count.ToString(); 
+2

將解決方案粘貼到此處,或者發表評論 – Guffa 2012-07-05 17:09:34

+0

@Guffa,對不起那我從鏈接中添加了解決方案。 – Drakkainen 2012-07-05 17:47:35

3

記住字符串是字符數組。

可以在LINQ查詢使用Enumerable.Count

"11.11.11".Count(c => c=='.'); // 2 
"1.1.1.1".Count(c => c=='.'); // 3 
2
string stringToTest = "1.11"; 
string[] split = stringToTest.Split('.'); 
int count = split.Length - 1; 
Console.WriteLine("Your string has {0} periods in it", count); 
相關問題