0

我有以下两个字符串:

字符串一:
“abcabc/xyzxyz/12345/random_num_09/somthing_random.txt”

字符串二:
“abcabc/xyzxyz/12345/”

我想做的是从字符串一两个字符串二附加路径“random_num_09/somthing_random.txt”。那么如何从字符串一中减去字符串二,然后将剩余部分附加到字符串二。

我试图通过在字符串一中搜索倒数第二个“/”然后执行子字符串并将其附加到字符串二来做到这一点。

但是有没有更好的方法呢。

谢谢。

4

2 回答 2

2

I think the best way is to use substrings, as you said:

String string_one = "abcabc/xyzxyz/12345/random_num_09/somthing_random.txt";
String string_two = "abcabc/xyzxyz/12345/";
String result = string_two + string_one.substring(string_one.indexOf(string_two)+1));

The other possibility is to use regex, but you would still be doing concatenation to get the result.

Pattern p = Pattern.compile(string_two+"(.*)");
Matcher m = p.matcher(string_one);
if (m.matches()) {
  String result = string_two+m.group(1);
}
于 2013-06-06T12:01:48.313 回答
2

而不是一个子字符串,replace 更易于使用:

String string1 = "abcabc/xyzxyz/12345/random_num_09/somthing_random.txt";
String string2 = "abcabc/xyzxyz/12345/";
String res = string2 + string1.replace(string2, "");
于 2013-06-06T12:03:48.260 回答