public void setCharAt(int index, char ch)
参数
-
index -- 这是要修改字符的索引。
-
ch -- 这是新的字符
str.toString
返回字符串本身
问题:Error:(31, 40) java: 不兼容的类型: java.lang.String无法转换为java.lang.StringBuffer
字符串问题:
1.String对象是不可变得,String类中每一个看起来会修改String值的方法,实际上都是创建了一个新的String对象,以包含修改后的字符串内容。而最初的String对象则丝毫未动,
2.
有错误的代码
public class Solution {
public static String replaceSpace(StringBuffer str) {
int spaceNum=0;
for(int i=0;i<str.length();i++){
if(str.charAt(i)==' '){
spaceNum++;
}
}
int indexOld=str.length()-1;
int newLength=str.length()+spaceNum*2;
int indexNew=newLength-1;
str.setLength(newLength);
for( ;indexOld>=0&&indexOld<newLength;--indexOld) {
if (str.charAt(indexOld) == ' ') {
str.setCharAt(indexNew--, '0');
str.setCharAt(indexNew--, '2');
str.setCharAt(indexNew--, '%');
} else {
str.setCharAt(indexNew, str.charAt(indexOld));
}
indexNew--;
}
return str.toString();
}
public static void main(String []args){
StringBuffer StrNew=new StringBuffer("we are happy");
System.out.println(replaceSpace(StrNew));
}
}
错误:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.StringBuffer.setCharAt(StringBuffer.java:255)
at Solution.replaceSpace(Solution.java:23)
at Solution.main(Solution.java:31)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
原因:字符串边界问题,越界了
改正后代码
public class Solution {
public static String replaceSpace(StringBuffer str) {
int spaceNum=0;
for(int i=0;i<str.length();i++){
if(str.charAt(i)==' '){
spaceNum++;
}
}
int indexOld=str.length()-1;
int newLength=str.length()+spaceNum*2;
int indexNew=newLength-1;
str.setLength(newLength);
for( ;indexOld>=0&&indexOld<newLength;indexOld--) {
if (str.charAt(indexOld) == ' ') {
str.setCharAt(indexNew--, '0');
str.setCharAt(indexNew--, '2');
str.setCharAt(indexNew--, '%');
} else {
str.setCharAt(indexNew--,str.charAt(indexOld));
}
}
return str.toString();
}
public static void main(String []args){
StringBuffer StrNew=new StringBuffer("we are happy");
System.out.println(replaceSpace(StrNew));
}
}
运行结果:
we%20are%20happy
Process finished with exit code 0