Domanda

Non sono sicuro di come fare questo. In questo momento sto contando gli spazi per ottenere il numero di parole di mia stringa, ma se c'è un doppio spazio il numero di parola sarà impreciso. C'è un modo migliore per fare questo?

È stato utile?

Soluzione

versione alternativa di @ Martin v. Löwis, che utilizza un foreach e char.IsWhiteSpace() che dovrebbe essere più corretto quando si tratta di altre culture.

int CountWithForeach(string para)
{
    bool inWord = false;
    int words = 0;
    foreach (char c in para)
    {
        if (char.IsWhiteSpace(c))
        {
            if( inWord )
                words++;
            inWord = false;
            continue;
        }
        inWord = true;
    }
    if( inWord )
        words++;

    return words;
}

Altri suggerimenti

Mentre le soluzioni basate su Split sono brevi di scrivere, si potrebbe ottenere costoso, come tutti gli oggetti stringa devono essere creati e poi gettato via. Mi aspetterei che un algoritmo esplicito come

  static int CountWords(string s)
  {
    int words = 0;
    bool inword = false;
    for(int i=0; i < s.Length; i++) {
      switch(s[i]) {
      case ' ':case '\t':case '\r':case '\n':
          if(inword)words++;
          inword = false;
          break;
      default:
          inword = true;
          break;
      }
    }
    if(inword)words++;
    return words;
  }

è più efficiente (più esso può anche prendere in considerazione spazi bianchi supplementari).

Questo sembra funzionare per me:

var input = "This is a  test";
var count = input.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Length;

String.split :

string sentence = "This     is a sentence     with  some spaces.";
string[] words = sentence.Split(new char[] { ' ' },  StringSplitOptions.RemoveEmptyEntries);
int wordCount = words.Length;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top