将空格替换成“abc”
方法一:
使用java的API,String.replace()方法的简单实现。
public class Main {
public static void main(String[] args) {
String s = "1 2 3 4 5 6 7 8 9 0";
s = method(s);
System.out.println(s);
}
private static String method(String s) {
if (s == null || s.length() <= 0) {
return null;
}
return s.replace(" ", "abc");
}
}
方法二:
使用java的API,StringBuffer.append()方法的简单实现。
public class Main {
public static void main(String[] args) {
String s = "1 2 3 4 5 6 7 8 9 0";
s = method(s);
System.out.println(s);
}
private static String method(String s) {
if (s == null || s.length() <= 0) {
return null;
}
StringBuffer sb = new StringBuffer();
for (int i = 0; i < s.length(); i++) {
if(s.charAt(i) == ' '){
sb.append("abc");
}else{
sb.append(s.charAt(i));
}
}
return sb.toString();
}
}
方法三:
自己编写方法,算法实现。
public class Main {
public static void main(String[] args) {
String s = "1 2 3 4 5 6 7 8 9 0";
s = method(s);
System.out.println(s);
}
private static String method(String s) {
if (s == null || s.length() == 0) {
return null;
}
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == ' ') {
count++;
}
}
int oldLen = s.length();
int newLen = s.length() + 2 * count;
char[] newc = new char[newLen];
System.arraycopy(s.toCharArray(), 0, newc, 0, s.length());
int i = oldLen - 1, j = newLen - 1;
while (i >= 0 && i < j) {
if (newc[i] == ' ') {
newc[j--] = 'c';
newc[j--] = 'b';
newc[j--] = 'a';
} else {
newc[j--] = newc[i];
}
i--;
}
String newStr = new String(newc);
return newStr;
}
}
性能比较
把原字符串长度扩大十倍后,得到大概的运行时间如下。
注意点:
- String类型的变量值不能修改,为了防止产生大量字符串对象,系统在内部定义了字符串常量池。
- java API 的方法中包含了动态扩展数组长度的功能。
- 如果原字符序列的长度不够,一定要动态开辟数组空间,否则数组下标越界。