如何在字符串中查找空格?

68

如何检查一个字符串是否包含空格字符、空白字符或 " "。如果可能,请提供一个Java示例。

例如:String = "test word";

Java示例代码: boolean containsWhitespace = str.contains(" ");

3
“空间”是什么? 它是“空无一物”吗? - Dominic Rodger
10
@Dominic - 当你清空一个“满的空间”时,你得到的就是这个结果。显然!!! - Stephen C
14个回答

-1
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);

-1
我向您提供一种非常简单的方法,使用 String.contains
public static boolean containWhitespace(String value) {
    return value.contains(" ");
}

一个小的使用例子:
public static void main(String[] args) {
    System.out.println(containWhitespace("i love potatoes"));
    System.out.println(containWhitespace("butihatewhitespaces"));
}

输出:

true
false

-1

使用org.apache.commons.lang.StringUtils。

  1. 搜索空格

boolean withWhiteSpace = StringUtils.contains("my name", " ");

  1. 删除字符串中的所有空格

StringUtils.deleteWhitespace(null) = null StringUtils.deleteWhitespace("") = "" StringUtils.deleteWhitespace("abc") = "abc" StringUtils.deleteWhitespace(" ab c ") = "abc"


-2
package com.test;

public class Test {

    public static void main(String[] args) {

        String str = "TestCode ";
        if (str.indexOf(" ") > -1) {
            System.out.println("Yes");
        } else {
            System.out.println("Noo");
        }
    }
}

2
请解释你为什么这么做,以及为什么那是解决方案。请注释你的代码! - ReneS
1
这段代码无法找到很多空格。 - james.garriss

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接