2011-05-22 68 views
3

如何統計字符數&數組中的字在C#中?統計數組中的字符數和字數

對於例如爲:

char[] arr= "My name is ABC XYZ".Tochararray(); 

應該返回5看作單詞和18的數(空間被算作字符)作爲字符數。

謝謝!

+2

這是一個字符串,而不是一串整數。 – BoltClock 2011-05-22 13:48:29

+0

表示正確!問題已更新 – 2011-05-22 13:56:21

回答

4

您不能直接串在C#中分配到整數/字符數組

string s = "My name is ABC XYZ"; 

int l = s.Length // 18 chars; 
int w = s.Split(' ').Count(); // 5 words 
4

下面是一個使用LINQ的瑣碎(空基)字數:

string s = "My name is ABC XYZ"; 
int l = s.Length;     // 18 
int w = s.Count(x => x == ' ') + 1; // 5 

這通常會比調用Split()更好,因爲它將字符串處理爲可枚舉的字符流,並隨着它的行進而進行計數,而不是創建一組字符串來存儲單詞。