How to print the number of words in a string that receives a sentence in .NET?

2

I would like to print the number of words in a sentence declared within a string .

Example:

string frase = "Meu carro vermelho é caro"
cont = 0;
aux = -1;

while(frase.lenght() < frase =="") {
    aux++;
    if(cont < aux){
      cont++;
    }
    Console.writeln(cont);
}
    
asked by anonymous 13.09.2016 / 02:48

3 answers

4

Split and a strings method that transforms the original string into an array , using a character as a ' .

So you just need to know the total size of the resultant array - this will be the total of words.

using System;

public class Program
{
    public static void Main()
    {
        string frase = "Meu carro vermelho é caro"; 
        string[] palavras = frase.Split(' '); 
        int totalPalavras = palavras.Length;

        Console.WriteLine(totalPalavras);
    }
}
    
13.09.2016 / 02:56
4

Use Split and Array length :

Split splits a string into parts according to specification or specifications in your method.

Array length brings the quantity of items contained in an array.

string frase = "Meu carro vermelho é caro";
string[] palavras = frase.Split(new char[] {' '});
Console.WriteLine(palavras.Length);

Example

References:

String.Split Method (String [], StringSplitOptions)

Array.Length Property

    
13.09.2016 / 02:56
-1

Here is a simple example of easy implementation:

using System;
using System.Text;

public class StringClassTest
{
   public static void Main()
   {
      string characters = "abc\u0000def";
      Console.WriteLine(characters.Length);    // Displays 7
   }
}

Source: link

    
13.09.2016 / 18:04