2017-05-11 41 views
3

所以乾脆: 所有我想要的是:如何計算兩個引號之間的文本?

輸入:嘿 「有我在想你」 「再一次」

輸出:2

Inpu噸:嘿「我在想你」「再一次」「開玩笑」

輸出:3

計數的空間從來沒有與我工作是因爲:有引號之間我測試,但從未工作過,因爲上面的原因

代碼文本空間...

static int CountWords(string text) 
{ 
    int wordCount = 0, index = 0; 

    while (index < text.Length) 
    { 

     while (index < text.Length && !char.IsWhiteSpace(text[index])) 
      index++; 

     wordCount++; 

     while (index < text.Length && char.IsWhiteSpace(text[index])) 
      index++; 
    } 
    return wordCount; 
} 

回答

4

正則表達式將工作奇妙在這裏:

var count = Regex.Matches(input, "\".*?\"").Count; 

另外,由兩個計數引號的數量,然後將其他建議,將工作一樣好:

var count = input.Count(c => c == '"')/2; 
+0

你打敗了我。這是一個[小提琴](https://dotnetfiddle.net/Y2zJTM)它的行動 – maccettura

0

你可以指望的報價併除以2.

int counter = 0; 
int answer = 0; 

foreach (char c in input) 
{ 
    if(c == "\"") 
    { 
     counter++; 
    } 
} 

answer = counter/2; 
0

會是這樣的工作嗎?

int numQuotes = text.Split('"').Length - 1; 
wordCount = numQuotes/2; 
+0

的'拆分「的方法很聰明,但我寧願不分配一個新的數組來確定它的長度。 – Abion47

相關問題