[英]replacing characters of a string
因此,我试图遍历字符串,并用新值替换给定子字符串的任何出现。 我似乎无法弄清楚我的代码有什么问题,因为它似乎没有对我运行的字符串进行任何更改。
我创建了一个新字符串nS,它以“”开头,并遍历模板,将每个字符视为子字符串s。 在每种情况下,都需要用一个值替换某些东西,我将所述值附加到nS上,否则它将仅按原样附加当前子字符串。
@Override
public String format(String template) {
String nS = "";
for (int i = 0, n = template.length(); i < n; i++) {
String s = template.substring(i, i + 1);
switch (s) {
case "%%":
nS = nS.concat("%");
break;
case "%t":
nS = nS.concat(String.valueOf(inSeconds()));
break;
}
}
return nS;
}
实际的代码还有更多的情况,但我把它们排除在外,以至于不至于使人难以理解。
2-arg substring
方法中的结尾索引是Exclusive 。
子字符串从指定的beginIndex开始,并扩展到索引endIndex-1处的字符。
beginIndex-起始索引(含)。
endIndex-结束索引(不包括)。
您将得到一个仅一个字符而不是2个字符的子字符串。在进行适当的边界检查之后,尝试i + 2
:
String s = template.substring(i, i + 2);
假设性能不是我要解决的大问题
public String format(String template) {
return template.replaceAll ("%%", "\uffff")
.replaceAll("%t", ""+inSeconds())
.replaceAll("\uffff", "%");
}
您所描述的尝试执行的操作听起来像是您试图重写String.replace()
给定String s =“我的名字叫鲍伯”
并且您想用“ Susan”替换“ Bob”,您需要做的是:
String s = "My Name is Bob";
String n = s.replace("Bob", "Susan");
System.out.println(n); //My Name is Susan
System.out.println(s); //My Name is Bob
另一种选择是将字符串分成一个字符数组并对其进行迭代。
String s = "My Name is Bob";
char[] bits = s.toCharArray();
for(char c : bits) {
// logic
}
一次比较两个字符:
String s = "My Name is Bob";
char[] bits = s.toCharArray();
for(int i = 0; i < bits.length; i++) {
if(i + 1 <= bits.length) {
String searchFor = "" + bits[i] + bits[i + 1];
// logic
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.