Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding Spaces, Newlines and Tabs with charAt()

Tags:

java

android

I'm trying to check if there is a space, a newline or a tab at the current character location. Spaces work but tabs and newlines dont. Go figure, I'm using escapes for those, and just a regular space for a space... What's the correct way to find these at a location?

if(String.valueOf(txt.charAt(strt)).equals(" ") || 
                    txt.charAt(strt) == '\r' ||
                    txt.charAt(strt) == '\n' || 
                    txt.charAt(strt) == '\t') {
    //do stuff
                    }
like image 232
bwoogie Avatar asked Oct 19 '11 01:10

bwoogie


People also ask

Does charAt count spaces?

Yes, the character count includes all spaces, punctuation and letters. Anything that moves your cursor counts as a character.

What does the charAt () method will do?

The charAt() method returns the character at the specified index in a string. The index of the first character is 0, the second character is 1, and so on.

Can charAt return multiple characters?

charAt() returns a single character. It does not return a range of characters.

What is the data type of the output returned by charAt () method?

The Java String class charAt() method returns a char value at the given index number. The index number starts from 0 and goes to n-1, where n is the length of the string. It returns StringIndexOutOfBoundsException, if the given index number is greater than or equal to this string length or a negative number.


2 Answers

This works for me:

  char c = txt.charAt(strt);
  if (c == ' ' || c == '\t' || c == '\n' || c == '\r')
    System.out.println("Found one at " + strt);

Yours works too, although it's a bit harder to follow. Why it doesn't work for you I don't know - maybe the string is badly formed? Are you sure you actually have tabs and stuff in it?

like image 117
Amadan Avatar answered Oct 06 '22 20:10

Amadan


It should work just fine, check your input string. Also, the space can be checked by comparing a blank space character. Creating a new String object just for comparison is costly.

like image 23
Saurabh Saxena Avatar answered Oct 06 '22 18:10

Saurabh Saxena