【问题标题】:How to check if there is a space between two characters?如何检查两个字符之间是否有空格?
【发布时间】:2015-03-07 22:40:10
【问题描述】:

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

【问题讨论】:

  • 请添加您目前尝试过的代码。
  • 我找到了一个更简单的解决方案:不是在每个字符后添加一个空格,而是我想我可以在每个符号前后添加一个空格:theString.replace("symbol", "symbol");

标签: java string swing char jtextfield


【解决方案1】:

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

此正则表达式允许轻松修改,进一步限制或允许某些组合 - 轻松允许数字而不是数字。您可能希望在实用程序类中使用已编译的最终模式:

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

给定输出:

字符串无效:1+2

字符串有效:2 + 3

字符串有效:5 + 6 - 4

字符串无效:1 +

字符串无效:6 6

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

    • 是的,数字不仅仅是一个数字,它们最多可以是 10 位数字。
    【解决方案3】:

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

    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("");
    }
    

    【讨论】:

      【解决方案4】:

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

      String str = textField.getText();
      

      然后你可以通过去看看它是否有空格。

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-12-16
        • 2018-10-09
        • 2016-05-17
        • 1970-01-01
        • 2010-12-31
        • 2015-05-10
        • 2011-05-29
        相关资源
        最近更新 更多