How can I find whitespace in a String?

后端 未结 14 1025
感动是毒
感动是毒 2020-12-01 05:08

How can I check to see if a String contains a whitespace character, an empty space or \" \". If possible, please provide a Java example.

For example: String

相关标签:
14条回答
  • 2020-12-01 05:25

    Use this code, was better solution for me.

    public static boolean containsWhiteSpace(String line){
        boolean space= false; 
        if(line != null){
    
    
            for(int i = 0; i < line.length(); i++){
    
                if(line.charAt(i) == ' '){
                space= true;
                }
    
            }
        }
        return space;
    }
    
    0 讨论(0)
  • 2020-12-01 05:27
    String str = "Test Word";
                if(str.indexOf(' ') != -1){
                    return true;
                } else{
                    return false;
                }
    
    0 讨论(0)
  • 2020-12-01 05:28

    This will tell if you there is any whitespaces:

    Either by looping:

    for (char c : s.toCharArray()) {
        if (Character.isWhitespace(c)) {
           return true;
        }
    }
    

    or

    s.matches(".*\\s+.*")
    

    And StringUtils.isBlank(s) will tell you if there are only whitepsaces.

    0 讨论(0)
  • 2020-12-01 05:32

    Use Apache Commons StringUtils:

    StringUtils.containsWhitespace(str)
    
    0 讨论(0)
  • 2020-12-01 05:32
    import java.util.Scanner;
    public class camelCase {
    
    public static void main(String[] args)
    {
        Scanner user_input=new Scanner(System.in);
        String Line1;
        Line1 = user_input.nextLine();
        int j=1;
        //Now Read each word from the Line and convert it to Camel Case
    
        String result = "", result1 = "";
        for (int i = 0; i < Line1.length(); i++) {
            String next = Line1.substring(i, i + 1);
            System.out.println(next + "  i Value:" + i + "  j Value:" + j);
            if (i == 0 | j == 1 )
            {
                result += next.toUpperCase();
            } else {
                result += next.toLowerCase();
            }
    
            if (Character.isWhitespace(Line1.charAt(i)) == true)
            {
                j=1;
            }
            else
            {
                j=0;
            }
        }
        System.out.println(result);
    
    0 讨论(0)
  • 2020-12-01 05:36

    You could use Regex to determine if there's a whitespace character. \s.

    More info of regex here.

    0 讨论(0)
提交回复
热议问题