How to count the spaces of a String in java

0

Here is the example of the code you were doing:

package manipulacaos;
import java.util.Scanner;


public class ManipulacaoS {
    public static void main(String[] args){
     Scanner ler = new Scanner(System.in);

     String letra = "a";
     String s;
     int Ccount=0;
     int spacecount=0;


        System.out.println("Digite a String que quer informações..: ");
        s = ler.next();


        for( int i=0; i<s.length(); ){
            Ccount++;
            i++;
        }
        System.out.println("Essa palavra possui.: "+Ccount+" Caracteres.");

       for( int i=0; i<s.length(); i++ ){
         if( s.charAt(i) == ' ' ) {
          spacecount++;
        }
     }
        System.out.println("Essa palavra possui..: "+spacecount+" espacos.");

        int quantidade = s.length() - s.replaceAll(letra, "").length();
        System.out.println("Número de ocorrências da letra '" + letra + "': " + quantidade);
    }
    }
    
asked by anonymous 30.11.2017 / 13:20

2 answers

2

There's nothing wrong with your code, except you're using next() instead of nextLine() . The first can read the entry until there is a space, ie you can not read an "integer" string that has a space in the middle ( João Paulo = João ). nextLine will read the entire line , even with spaces in the middle, until you find \n ( João Paulo = João Paulo ).

That is, when you try to count the spaces it returns 0 precisely because there are none, it is correct. If you want the entire line to be considered, just change the next of your code by nextLine .

next reads and keeps the cursor on the same line. < nextLine reads and positions the cursor on the next line.

    
30.11.2017 / 14:11
0
int count = 0;
String s = "Conte os espaços desta String   ";
 for(int i=0; i<s.length(); i++ ){
  if( s.charAt(i) == ' ' ) {
   count++;
 }
}
    
30.11.2017 / 13:22