【问题标题】:Removing an int from a Line of String. Then, putting the int to a variable从字符串行中删除一个 int。然后,将 int 放入变量
【发布时间】:2014-01-02 17:49:30
【问题描述】:
String team1=z.nextLine(), team2;

int num1, num2;

num1 = z.Int();
team1 = z.nextLine();
team1 = team1.replaceAll("[0-9]","");

System.out.println(team1 + " " + num1);

我需要扫描一个内容为“Alpha Beta Gamma 52”的文本文件。字符串“Alpha Beta Gamma”必须放在 team1 中,52 必须放在 num1 中。当我使用 .replaceAll 时,它会删除阻碍我拥有整数的 52。

【问题讨论】:

    标签: java string int java.util.scanner


    【解决方案1】:

    正如您所注意到的,一旦您从字符串中删除了值;该值不在字符串中。换成这样的怎么样?

    public static void main(String[] args) {
      String in = "Alpha Beta Gamma 52";
      String[] arr = in.split(" ");                // split the string by space.
      String end = arr[arr.length - 1];            // get the last "word"
      boolean isNumber = true;
      for (char c : end.trim().toCharArray()) {    // check if every character is a digit.
        if (!Character.isDigit(c)) {
          isNumber = false;                        // if not, it's not a number.
        }
      }
      Integer value = null;                        // the numeric value.
      if (isNumber) {
        value = Integer.valueOf(end.trim());
      }
      if (value != null) {
        in = in.substring(0, in.length()
            - (String.valueOf(value).length() + 1)); // get the length of the 
                                                     // numeric value (as a String).
      }
      // Display
      if (value != null) {
        System.out.printf("in = %s, value = %d", in, value);
      } else {
        System.out.println(in + " does not end in a number");
      }
    }
    

    【讨论】:

      【解决方案2】:

      在数字前拆分,然后解析部分:

      String[] parts = str.split(" (?=\\d)");
      String team = parts[0];
      int score = Integer.parseInt(parts[1]);
      

      【讨论】:

        【解决方案3】:
        public static void main(String[] args) {
        
                String readLine = new Scanner(System.in).nextLine();
        
                String team1 = readLine.replaceAll("\\d", "");
                int team2 = Integer.parseInt(readLine.replaceAll("\\D", ""));
        
                System.out.println(team1); //Alpha Beta Gamma
                System.out.println(team2); //52    
        
        }
        

        【讨论】:

        • 对于第二个替换正则表达式,我推荐使用\\D:replaceAll("\\D","")。这将删除 所有 个非数字。
        • 我想保留它们,而不是删除它们
        • 我说的是第二个正则表达式。在那里,您只想保留数字。 \D 匹配所有非数字,因此 readLine.replaceAll("\\D",""); 将返回一个仅包含数字的 String。要扩展到包含 - 符号,我的正则表达式如下:[^\d-]
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-20
        • 2016-11-09
        • 1970-01-01
        • 2021-04-19
        相关资源
        最近更新 更多