IndexOf for Space in String

IndexOf for Space in String

There is a space in the string, but when I run program, it returns -1, that means there aren't spaces in the string Here's the code:

import java.util.Scanner;


public class Main {

     public static void main(String[] args) {
         Scanner scan = new Scanner(System.in);
         String s = scan.next();
         System.out.println(s.indexOf(' '));
    }

}

5 Answers

Scanner.next() returns the next token in the input, and by default, tokens are whitespace separated. i.e. s is guaranteed not to contain spaces.

Maybe you meant String s = scan.nextLine();?

this perfectly works fine for me.

System.out.println("one word".indexOf(' '));

This is because of Scanner next method. check this

Scanner reads text seperated by whitespace, which can be a line break but also a space character. This is why scan.next() will return a String with no spaces. If you need line breaks instead, use scan.nextLine()

Try

String s = scan.nextLine();

as scan.next() gets the next "word" which can't contain spaces.

Use scan.nextLine() because scan.next() will read until it encounters a white space (tab, space, enter) so it finish getting when it see space. You yourself could guess this by printing s, too! be successful!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Marcus Vance
Author

Marcus Vance

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.