《剑指offer》面试题的Java实现-替换空格

题⽬描述:请实现⼀个函数,将⼀个字符串中的每空格替换成“%20”。例如,当字符串为We Are Happy,则经过 替换之后的字符串为We%20Are%20Happy。

 

解法一:调用API

public static String solution3_1(String str){
return str.replace(" ","%20");
}

解法二:通过new一个StringBuffer类,如果遍历到空格就追加%20,没有遍历到就正常将字符串追加到StringBuffer中。
public static String solution3_2(String str){
StringBuffer sb = new StringBuffer();
for (int i = 0; i < str.length(); i++) {
if(str.charAt(i)==' '){
sb.append("%20");
}else{
sb.append(str.charAt(i));
}
}
return sb.toString();
}

解法三:先获取原字符串的长度,以及空格的个数,然后创建一个char类型的数组,将获取到的长度+空格的个数*2就是新的char类型数组的长度,将原字符串遍历到新char类型的数组中去,就是替换后的字符串。
public static String solution3_3(String str){
int length = str.length();//6
int spaceCount = 0;
//获取空格数量,因为要new一个新的容量
for (int i = 0; i < str.length(); i++) {
if(str.charAt(i) == ' '){
spaceCount ++;
}
}

int newCountLength = length + spaceCount*2; //8
char [] newChar = new char[newCountLength];
int count = 0 ;
for (int i = 0; i < str.length(); i++) {
if(!(str.charAt(i) == ' ')){
newChar[count++] = str.charAt(i);
}else{
newChar[count++] = '%';
newChar[count++] = '2';
newChar[count++] = '0';

}
}
return new String(newChar);
}
posted @   深海、  阅读(16)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示