【问题标题】:Reading and replacing Integers in a string读取和替换字符串中的整数
【发布时间】:2013-04-17 18:00:46
【问题描述】:

我有一个字符串,例如“x(10, 9, 8)”我想从字符串中读取每个整数,然后使用整数作为数组索引从数组中检索一个新整数并用这个值替换它。

我尝试过的所有方法似乎都更适合将相同的东西应用于所有整数,或者只是检索整数然后失去对它们的跟踪。谁能告诉我最好的方法吗?

【问题讨论】:

  • 总是3个数字吗?
  • 你能给出你试过的代码吗?为什么不能将字符串解析成临时数组避免丢失值?
  • 抢劫就是这样,不可以是1-4个数字
  • 所以在这种情况下,如果你的数组是 [10,9,8,7,6,5,4,3,2,1,0],你会想要一个字符串 " x(0,1,2)" 结果呢?

标签: java string integer


【解决方案1】:

使用正则表达式,您可以“浏览”字符串中的每个数字,无论它们是如何分隔的,并根据需要替换它们。例如,下面的代码打印x(101, 99, 88):

public static void main(String[] args) {
    int[] array = {0, 1, 2, 3, 4, 5, 6, 7, 88, 99, 101};
    String s = "x(10, 9, 8)";

    Pattern p = Pattern.compile("\\d+");
    Matcher m = p.matcher(s);
    StringBuilder replace = new StringBuilder();
    int start = 0;
    while(m.find()) {
        //append the non-digit part first
        replace.append(s.substring(start, m.start()));
        start = m.end();
        //parse the number and append the number in the array at that index
        int index = Integer.parseInt(m.group());
        replace.append(array[index]);
    }
    //append the end of the string
    replace.append(s.substring(start, s.length()));

    System.out.println(replace);
}

注意:你应该添加一些异常处理。

【讨论】:

    【解决方案2】:

    使用Integer.parseInt()String.split(",")String.indexOf() 解析字符串的数字(对于()。用它们创建一个List

    遍历此列表并使用数组中的值创建一个新列表。

    遍历新列表并创建响应字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-05
      • 1970-01-01
      • 1970-01-01
      • 2016-08-09
      • 1970-01-01
      • 2017-04-25
      相关资源
      最近更新 更多