How to print the amount of words in a string that gets a sentence in . NET?

Asked

Viewed 620 times

2

I would like to print the amount 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);
}

3 answers

4

  • 1

    +1 by placing the references of the methods used

4

Split and a method of strings that transforms the string original in a array, using a character as a cut parameter'.

So, you just need to know the total size of the array resulting - 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);
    }
}
  • Just fix the syntax errors, perfect.

  • @Virgilionovic Damn mixture of Javascript syntax and C#. ;) Thanks for pointing out the error.

  • No problem @Onosendai, I also soon error by knowing two languages and I end up confused everything ... normal ... just was really a warning!

-1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.