简体   繁体   中英

Finding Spaces, Newlines and Tabs with charAt()

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
                    }

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.

This regex [\\s] will do the work. It matches the whitespace, Equivalent to [\\t\\n\\r\\f].

Looking at the docs for Editable in android, it returns a char . Therefore ...

if (txt.charAt(strt) == ' ' || 
    txt.charAt(strt) == '\r' ||
    txt.charAt(strt) == '\n' || 
    txt.charAt(strt) == '\t') 
{
    //do stuff
}

Will produce the expected result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM