![](/img/trans.png)
[英]Java: Replace a specific character with a substring in a string at index
[英]java replace substring in string specific index
如何使用算法“用01替換最后一個子串10”,用10010
替換字符串10100
。 我試過了
s=s.replace(s.substring(a,a+2), "01");
但這會返回01010
,替換"10"
的第一個和第二個子串。 “a”代表s.lastindexOf(“10”);
這是一個可以使用的簡單且可擴展的功能。 首先是它的使用/輸出然后是它的代碼。
String original = "10100";
String toFind = "10";
String toReplace = "01";
int ocurrence = 2;
String replaced = replaceNthOcurrence(original, toFind, toReplace, ocurrence);
System.out.println(replaced); // Output: "10010"
original = "This and This and This";
toFind = "This";
toReplace = "That";
ocurrence = 3;
replaced = replaceNthOcurrence(original, toFind, toReplace, ocurrence);
System.out.println(replaced); // Output: "This and This and That"
public static String replaceNthOcurrence(String str, String toFind, String toReplace, int ocurrence) {
Pattern p = Pattern.compile(Pattern.quote(toFind));
Matcher m = p.matcher(str);
StringBuffer sb = new StringBuffer(str);
int i = 0;
while (m.find()) {
if (++i == ocurrence) { sb.replace(m.start(), m.end(), toReplace); break; }
}
return sb.toString();
}
如果要訪問字符串的最后兩個索引,則可以使用: -
str.substring(str.length() - 2);
這將為您提供從索引str.length() - 2
到last character
,這正好是最后兩個字符。
現在,您可以使用您想要的任何字符串替換最后兩個索引。
更新 : -
如果要訪問最后一個字符或子字符串,可以使用String#lastIndexOf
方法: -
str.lastIndexOf("10");
好的,你可以試試這個代碼: -
String str = "10100";
int fromIndex = str.lastIndexOf("10");
str = str.substring(0, fromIndex) + "01" + str.substring(fromIndex + 2);
System.out.println(str);
您可以使用字符串的lastIndexOf方法獲取字符或子字符串的最后一個索引。 請參閱下面的文檔鏈接以了解如何使用它。
http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#lastIndexOf(java.lang.String )
一旦知道了子字符串的索引,就可以獲得該索引之前所有字符的子字符串,以及搜索字符串中最后一個字符之后所有字符的子字符串,並進行連接。
這有點抽出,我實際上沒有運行它(所以我可能有語法錯誤),但它給你的重點是我至少要傳達的東西。 如果你願意,你可以在一行中完成這一切,但它也不能說明這一點。
string s = "10100";
string searchString = "10";
string replacementString = "01";
string charsBeforeSearchString = s.substring(0, s.lastIndexOf(searchString) - 1);
string charsAfterSearchString = s.substring(s.lastIndexIf(searchString) + 2);
s = charsBeforeSearchString + replacementString + charsAfterSearchString;
10100 with 10010
String result = "10100".substring(0, 2) + "10010".substring(2, 4) + "10100".substring(4, 5);
最簡單的方法:
String input = "10100";
String result = Pattern.compile("(10)(?!.*10.*)").matcher(input).replaceAll("01");
System.out.println(result);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.