Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

}
like image 673
Filipp Maksimov Avatar asked Mar 31 '12 14:03

Filipp Maksimov


People also ask

How do I check if a string contains spaces?

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.

What is the index of a space in Java?

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).

How do you index the first space of a 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.

Can we use space in string?

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.


2 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();?

like image 78
Mat Avatar answered Oct 29 '22 04:10

Mat


this perfectly works fine for me.

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

This is because of Scanner next method. check this

like image 27
Balaswamy Vaddeman Avatar answered Oct 29 '22 05:10

Balaswamy Vaddeman