如何使用“用01替换最后一个子串10”算法将字符串10100
替换为10010
。我试过了
s=s.replace(s.substring(a,a+2), "01");
但这将返回01010
,替换"10"
的第一个和第二个子字符串。A表示s.lastindexOf("10");
发布于 2013-05-23 10:21:47
下面是一个简单且可扩展的函数,您可以使用它。首先是它的使用/输出,然后是它的代码。
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();
}
发布于 2012-10-27 02:30:41
如果你想访问字符串的最后两个索引,那么你可以使用:-
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);
发布于 2012-10-27 02:31:31
可以使用string的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;
https://stackoverflow.com/questions/13092406
复制相似问题