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(' '));
}
}
In order to check if a String has only unicode digits or space in Java, we use the isDigit() method and the charAt() method with decision making statements. The isDigit(int codePoint) method determines whether the specific character (Unicode codePoint) is a digit. It returns a boolean value, either true or false.
If you're looking for the index of the space between "javaranch" and "big", use indexOf(String). If you want the index of the LAST space, i.e. the one between "moose" and "saloon", use lastIndexOf(String).
int indexOf(String str, int strt) : This method returns the index within this string of the first occurrence of the specified substring, starting at the specified index. If it does not occur, -1 is returned. Syntax: int indexOf(String str, int strt) Parameters: strt: the index to start the search from.
We then place spaces before those characters. Example 3: Input: s = "spacing", spaces = [0,1,2,3,4,5,6] Output: " s p a c i n g" Explanation: We are also able to place spaces before the first character of the string.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With