Если у вас есть несколько экземпляров одной и той же подстроки для замены, вы можете использовать replace . Однако если вам нужно заменить экземпляр nth
, вы можете определить свою функцию, как показано ниже.
public class Main {
public static void main(String[] args) {
String url = "/student/:id/xyz/:id/abc/one/:id/two/three/:id/four";
// A test id
int id = 123;
// Replace all occurrences of :id
String urlAll = url.replace(":id", String.valueOf(id));
System.out.println(urlAll);
// Replace nth (0-based) e.g. 0th occurrence of :id
String url0 = replaceNthSubstr(url, ":id", 0, id);
System.out.println(url0);
// Replace nth (0-based) e.g. 2nd occurrence of :id
String url2 = replaceNthSubstr(url, ":id", 2, id);
System.out.println(url2);
// Replace nth (0-based) e.g. 3rd occurrence of :id
String url3 = replaceNthSubstr(url, ":id", 3, id);
System.out.println(url3);
}
/**
*
* @param str - The string in which substr is to be substituted with val
* @param substr - The substring to be replaced in str
* @param n - The nth (0-based) substr
* @param val - The value to substitute substr
* @return If the substitution is successful, a new string with substituted
* value will be returned. Otherwise, str will be returned.
*/
static String replaceNthSubstr(String str, String substr, int n, int val) {
if (str == null || substr == null) {
return str;
}
String strVal = String.valueOf(val);
int pos = -1;
do {
pos = str.indexOf(substr, pos + 1);
} while (n-- > 0 && pos != -1);
return pos != -1 ? str.substring(0, pos) + strVal + str.substring(pos + substr.length()) : str;
}
}
Вывод:
/student/123/xyz/123/abc/one/123/two/three/123/four
/student/123/xyz/:id/abc/one/:id/two/three/:id/four
/student/:id/xyz/:id/abc/one/123/two/three/:id/four
/student/:id/xyz/:id/abc/one/:id/two/three/123/four