How to count the spaces of a String in java

Asked

Viewed 873 times

0

Here I followed the example of the code I was making:

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);
    }
    }

2 answers

2


There’s nothing wrong with your code, except that you’re using next() instead of nextLine(). The first can read the input until there is a space, that is, you cannot read an "entire" string that has a space in the middle (João Paulo = João). Already the 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 just because there is none, it is correct. If you want to be considered the whole line, just change the next of its code by nextLine.

next reads and holds the cursor on the same line.
nextLine reads and positions the cursor on the next line.

  • 1

    Thank you very much, I knew I was missing something kk thanks for the help.

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++;
 }
}
  • tested separately and worked , but when I test along with the other codes does not appear the number of spaces

  • only works if the variable is already set as its s, but if the user type does not count the spaces and only counts the characters before the space

Browser other questions tagged

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