如何检查两个字符之间是否有space?

How to check if there is a space between two characters?

我是 Java 编程新手,我现在正在开发一个简单的应用程序。 现在我专注于寻找解决此问题的方法:检查 JTextField 中包含的字符串是否在其每个字符之间包含空格,例如:“1 + 2 - 3 + 7”(每个字符之间都有空格),但是我找不到解决方案 atm。 你可以帮帮我吗? 提前致谢 ;)

您可以创建一个使用偶数索引的方法:

public boolean followsFormat(String string) {

    String testString = "";

    for (int i = 1; i < string.length(); i += 2) {
        testString += string.trim().substring(i, i + 1);
    }

    testString = testString.trim();
    return testString.equals("");
}

真正简单的解决方案就是编写一个 for 循环来获取每个偶数索引并检查它是否为字符。

public boolean hasRightSpacing(String str) {
    for (int i = 1; i < str.length(); i+= 2) {
        if (str.charAt(i) != ' ') {
            return false;
        }
    }
    return true;
}

显然,如果所有数字都不是一位数,您将需要做更多的工作。

好吧,要从文本字段中获取字符串,您可以去

String str = textField.getText();

那你去看看里面有没有space

boolean containSpace = false;
if(str.contains(" "))
{
    containSpace = true;
}

如果你想计算有多少 space,我想你可以使用 for 循环和字符。

int counter = 0;
for(int i = 0; i <= str.length; i++)
{
    if(str.charAt(i) == ' ')
    {    
        counter++;
    }
}

除了制作方法外,我建议使用 Pattern: ^(\d + )*\d$

此 Regex 允许轻松修改,以进一步限制或允许某些组合 - 轻松允许数字而不是数字。您可能希望在实用程序 class:

中使用已编译的最终模式
public static final Pattern P = Pattern.compile("^(\d \+ )*\d$");

测试用例:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

// [...] 

public static final Pattern P = Pattern.compile("^(\d [\+\-] )*\d$");

public static void main(String[] args) {
    final String[] testCases = {
        "1+2", "2 + 3", "5 + 6 - 4", "1 + ", "6 6"
    };
    
    for(String s:testCases) {
        final Matcher m = P.matcher(s);
        if(m.matches()) {
            System.out.println("String valid: " + s);
        } else {
            System.out.println("String invalid: " + s);
        }
    }
}

给定输出:

String invalid: 1+2

String valid: 2 + 3

String valid: 5 + 6 - 4

String invalid: 1 +

String invalid: 6 6