ABAJAVa ABAJAVa - 3 months ago 8
Java Question

want to find in which all index the 'space' comes in a given string

String str;
System.out.println("Enter the String: ");
Scanner s = new Scanner(System.in);
str=s.nextLine();
for(int i=0;i<str.length();i++)
{
System.out.println("Space is at index ="str.indexOf(' '));
}


If I enter the string = "a b c d"
Then I want to print space is at index 1,3,5.
But the o/p is printing only 1 till the end of string lenght.

Answer

Please check the javadoc of indexOf(int ch) method.

Returns the index within this string of the first occurrence of the specified character.

As you can see, you are just keeping printing the first occurrence of space in given string.

Try code below:

    public class Test {
    public static void main(String args[]){
        String str;
        System.out.println("Enter the String: ");
        Scanner s = new Scanner(System.in);
        str=s.nextLine();
        int count = 0;
        for(int i=0;i<str.length();i++)
        {
            if(str.charAt(i) == ' '){
                System.out.println("Space is at index =" + i ); 
                count++;
            }

        }
        System.out.println("The total number of space is: " + count);
    }
}