【问题标题】:How to filter integers and copy them to a new array from a String如何过滤整数并将它们从字符串复制到新数组
【发布时间】:2018-02-27 15:09:33
【问题描述】:

有一个字符串(任何字符串)。它可能不包含数字;

如何将该数组中包含的整数存储到 ArrayList 中。

尝试过

public ArrayList<Integer> toList() {
    String stringToList;
    ArrayList<Integer> l = new ArrayList<>();
    stringToList = this.toString(); // I am just copying the string from the object
    for (int i = 0; i < stringToList.length(); i++) {
        if(((Integer) stringToList.charAt(i)) instanceof Integer){
                 //Here store it into the arrayList
                }             
    }
    return l;
}

但显然它不起作用,因为演员表不是解决方案。有任何想法吗?谢谢。

【问题讨论】:

标签: java arraylist casting integer chars


【解决方案1】:

由于字符串中可能存在12等,所以不能直接使用charAt()。您可以将stringToList, 分开,然后使用Integer.parseInt()

public ArrayList<Integer> toList() {
    String stringToList;
    ArrayList<Integer> l = new ArrayList<>();
    stringToList = this.toString(); // I am just copying the string from the object
    String[] strings = stringToList.split(",\\s+");
    for (int i = 0; i < strings.length; i++) {
        try {
            l.add(Integer.parseInt(strings[i]));
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }
    return l;
}

【讨论】:

  • 它抛出一个异常。数字格式异常。就算被抓到了?为什么?
  • 基本上,字符串可以是任何String。所以不仅仅是“1, 2, 3”,而是任何,比如“a, sodcomsd, iowqowi, 2233, kdiqwdq, 123123”。请注意,它们用逗号分隔。我想在该字符串中获取这些整数并将它们存储到 arrayList
  • 我仍然只得到一个 2。
  • @ismael oliva 如果您有多个空格,请使用String[] strings = stringToList.split(",\\s+");
【解决方案2】:

可以拆分字符串,比如

String[] splits = stringToList.split(",");

然后使用 Integer.parseInt(splits[0]); 之类的东西将它们转换为整数并将它们存储在 ArrayList 中

【讨论】:

    【解决方案3】:

    代码示例: (Execution)

    import java.util.Arrays;
    import java.util.Scanner;
    
    public class Scann {
        Scanner s;
    
        Scann() {
            s = new java.util.Scanner(System.in);
            System.out.println("Enter string : \n");
    
            String str = s.nextLine();
            str = str.replaceAll("[^-?0-9]+", " ");
            System.out.println(Arrays.asList(str.trim().split(" ")));
        }
    
        public static void main(String args[]) {
    
            new Scann();
        }
    
    }
    

    描述:[^-?0-9]+

    + 一次到无限次,尽可能多次,按需回馈

    -?字符之一“-?”

    0-9 介于“0”和“9”之间的字符

    【讨论】:

      【解决方案4】:

      您可以使用 Character.isDigit 方法检查字符是否为数字。

      if (Character.isDigit(stringToList.charAt(0))){
          l.add((int)stringToList.charAt(0));
      }
      

      在添加到整数数组列表之前,将 char 转换为 int。

      【讨论】:

        【解决方案5】:

        解析、检查、转换、收集以一行的方式:

        此解决方案可以解析任何 String,因为它会在转换为 Integer 之前检查从 split 中提取的每个部分仅由数字组成(或前面带有减号)

        String str = "1 , 2, 2a, 3,    -14, b55";
        List<Integer> list =  Arrays.stream(str.split(","))
                                    .map(String::trim)
                                    .filter(s -> s.matches(""-?\\d+""))
                                    .map(Integer::valueOf)
                                    .collect(Collectors.toList());
        System.out.println(list);     // list : [1, 2, 3, -14]
        
        • 用逗号分割String
        • 为它创建一个Stream
        • 删除spaces 周围
        • 检查是否只有数字
        • 将每个元素转换为Integer
        • 将它们收集到List

        【讨论】:

        • 最后列表只返回 2
        • @ismaeloliva nope : ideone.com/XZkBqE ,在确定给函数提供什么之前打印你的字符串
        【解决方案6】:

        如果您使用的是 Java 8,您可以尝试以下方法:

        public ArrayList<Integer> toList(String input) {
            return Arrays.stream(input.split(","))
                         .map(String::trim)
                         .filter(s -> s.matches("\\b\\d+\\b"))
                         .map(Integer::valueOf)
                         .collect(Collectors.toCollection(ArrayList::new));
        
        }
        

        【讨论】:

          猜你喜欢
          • 2012-02-09
          • 2011-07-09
          • 2021-06-24
          • 1970-01-01
          • 1970-01-01
          • 2016-11-21
          • 2018-01-01
          • 1970-01-01
          • 2020-06-20
          相关资源
          最近更新 更多