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
}
Yes, the character count includes all spaces, punctuation and letters. Anything that moves your cursor counts as a character.
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.
charAt() returns a single character. It does not return a range of characters.
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.
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?
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.
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