Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/393.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 读取和替换字符串中的整数_Java_String_Integer - Fatal编程技术网

Java 读取和替换字符串中的整数

Java 读取和替换字符串中的整数,java,string,integer,Java,String,Integer,我有一个字符串,例如“x(10,9,8)”,我想从字符串中读取每个整数,然后使用该整数作为数组索引,从数组中检索一个新整数,并将其替换为该值 我尝试过的所有方法似乎都更适合将相同的东西应用于所有整数,或者只是检索整数,然后失去对它们的跟踪。有谁能告诉我最好的方法吗?使用正则表达式,您可以“浏览”字符串中的每个数字,不管它们是如何分隔的,并根据需要替换它们。例如,下面的代码打印x(101、99、88): 注意:您应该添加一些异常处理。使用正则表达式,您可以“浏览”字符串中的每个数字,不管它们是如何

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


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

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


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

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


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

使用
Integer.parseInt()
string.split(“,”
)和
string.indexOf()
(对于
)解析字符串的数字。用它们创建一个
列表

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


迭代新列表并创建响应字符串。

使用
Integer.parseInt()
String.split(“,”
)和
String.indexOf()
(用于
解析字符串的数字。用它们创建一个
列表

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


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

总是3个数字吗?你能给出你尝试的代码吗?为什么你不能将字符串解析成一个临时数组以避免丢失值?这就是rob的情况,不,它可以是1-4个数字。所以在这种情况下,如果你的数组是[10,9,8,7,6,5,4,3,2,1,0],你会想要得到一个字符串“x”(0,1,2)“结果是什么?总是3个数字吗?你能给出你尝试过的代码吗?为什么你不能将字符串解析成一个临时数组以避免丢失值?这就是rob的情况,不,它可以是1-4个数字所以在这种情况下,如果你的数组是[10,9,8,7,6,5,4,3,2,1,0],你会想要得到一个字符串“x(0,1,2)”?
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);
}