将char数组转换为带空格的int数组

时间:2014-10-27 22:04:08

标签: java

我已经浏览过这个。我有一个char数组[10 20 30]。我想将它转换为整数的int数组或ArrayList,这样我的int数组就变成了 int [] charToInt = {10,20,30}; 我需要最初的指导来解决这个问题。我不想要整个代码。只需要一个提示。我会编写提示。

提前致谢

3 个答案:

答案 0 :(得分:1)

已更新:以下是工作示例

import java.util.ArrayList;

public class Example {
  public static void main(String[] args) {
    char[] input = { '1', '0',  ' ', '2', '0', ' ', '3', '0'};
    ArrayList<Integer> output = extractIntegers(input);

    for (int i : output) {
      System.out.println(i);
    }
  }

  private static ArrayList<Integer> extractIntegers(char[] chars) {
    int start = -1;
    ArrayList<Integer> integers = new ArrayList<Integer>();
    for (int i = 0; i < chars.length; i++) {
      boolean isDigit = Character.isDigit(chars[i]);
      if (start != -1 && !isDigit) {
        integers.add(parseInt(chars, start, i));
        start = -1;
      } else if (start == -1 && isDigit) {
        start = i;
      }
    }
    if (start != -1) {
      integers.add(parseInt(chars, start, chars.length));
    }
    return integers;
  }

  private static int parseInt(char[] chars, int start, int stop) {
    return Integer.parseInt(new String(chars, start, stop - start));
  }
}
  1. 将此代码保存在名为Example.java
  2. 的文件中
  3. 编译$ javac Example.java
  4. 运行$ java Example

答案 1 :(得分:1)

将结构char的{​​{1}}数组转换为{'number', ' ', 'number', ' ', ... }数组的方法是:

int

示例:

public static int[] toIntArray(final char[] source) {
    if (source == null || source.length == 0) { // check for null or empty array
        return new int[0];
    }

    final String sourceAsStr = String.copyValueOf(source); // convert array to string
    final String[] numbers = sourceAsStr.split(" "); // split string on "space"; each part contains a number
    final int[] result = new int[numbers.length];

    for(int i = 0; i < numbers.length; i++) {
        try {
            result[i] = Integer.parseInt(numbers[i]);
        } catch (final NumberFormatException e) {
            // handle exception
            return new int[0]; // return empty array on exception
        }
    }
    return result;
}

结果:

System.out.println(Arrays.toString(toIntArray(new char[] {'1', '0', ' ', '2', '0', ' ', '3', '0'})));
System.out.println(Arrays.toString(toIntArray(new char[] {'1', '0', '-', '2', '0', '-', '3', '0'})));
System.out.println(Arrays.toString(toIntArray(null)));

答案 2 :(得分:-2)