JAVA学习笔记(4)
字符替换:
1.一个空格替换成两个##
eg:i am a student
public class HomeWork {
public static int getCount(char[] ch){
int count = 0;
for(int i=0;i<ch.length;i++){
if(ch[i] == ' '){
count++;
}
}
return count;
}
public static String replaceBlank(String str){
char[] ch = str.toCharArray();//把字符串转化成一个一个字符
int count = getCount(ch);
char[] chNew = Arrays.copyOf(ch,ch.length+count);
int i = 0,j = 0;
for (;i<ch.length;i++){
if (ch[i] != ' '){
chNew[j++] = ch[i];
}else {
chNew[j++] = '#';
chNew[j++] = '#';
}
}
return String.copyValueOf(chNew);
}
public static void main(String[] args) {
String str = "i am a student";
str = replaceBlank(str);
System.out.println(str);
}
}
2.一个任意字符 被替换成 任意个 任意字符
eg:i am a student
public class HomeWork {
public static int getCount(char[] ch,char x){
int count = 0;
for(int i=0;i<ch.length;i++){
if(ch[i] == x){
count++;
}
}
return count;
}
public static String replaceBlank(String str,char x, char chr, int times){
char [] ch = str.toCharArray();//字符串转化为字符
int count = getCount(ch,x) * (times - 1);
char [] chNew = Arrays.copyOf(ch,ch.length + count);
int i = 0,j = 0;
for(;i < ch.length;i++){
if(ch[i] != x){
chNew[j++] = ch[i];
}else{
for(int a = 0; a < times; a++) {
chNew[j++] = chr;
}
}
}
return String.copyValueOf(chNew);
}
public static void main(String[] args) {
String str = "i am a student";
str = replaceBlank(str,'a', '-', 3);
System.out.println(str);
}
}