实现一个函数,将字符串中的空格替换成"%20"
2016-10-10 11:14
387 查看
请实现一个函数,将字符串中的每个空格替换成"%20",例如输入"We are happy.",则输出"We%20are%20happy."
我的程序时间复杂度可以达到O(n),但是需要开辟一个新的字符串数组。
我的程序时间复杂度可以达到O(n),但是需要开辟一个新的字符串数组。
public class test { public static void main(String[] args) { String str = "We are happy."; char[] ch = str.toCharArray(); int len = ch.length; char[] ch1 = ReplaceBlank(ch, len); System.out.print(ch1); } public static char[] ReplaceBlank(char[] str, int len){ if(len<=0) return null; int count = 0; for(int i=0;i<len;i++){ if(str[i]==' ') ++count; //计数原字符串中的空格数目 } int newLength = len + count*2; char[] newStr = new char[newLength]; //替换后的字符串数组的大小 if(newLength == len) return null; int oldIndex = len-1; int newIndex = newLength-1; while(oldIndex>=0){ if(str[oldIndex]==' '){ newStr[newIndex--]='0'; newStr[newIndex--]='2'; newStr[newIndex--]='%'; }else{ newStr[newIndex--] = str[oldIndex]; } oldIndex--; } return newStr; } }
相关文章推荐
- 实现函数,用字符串&quot;%20&quot;替换空格
- [剑指offer][面试题04]实现一个函数,将字符串中的空格替换为“ ”.例如输入“we are happy.”,输出"we are happy.".
- 实现函数,用字符串"%20"替换空格
- 请实现一个函数,把字符串中的每个空格替换成“ ”
- 【c语言】字符串替换空格:请实现一个函数,把字符串中的每个空格替换成“%20”
- 【C语言】字符串替换空格:实现一个函数,把字符串里的空格替换成“%20”
- 【C语言】【面试题】【笔试题】.字符串替换空格:请实现一个函数,把字符串中的每个空格替换成“%20”。
- // 写一个函数,实现将一个字符串中的'/t'替换成四个'*', '/t'个数不定。如char *p="ht/thdsf/t/ttt/tfds dfsw/t ew/t",替换后p="ht****hdsf********tt****fds dfsw****
- 字符串替换空格:请实现一个函数,把字符串中的每个空格替换成“%20。
- 编写一个业务函数,实现字符串(前后各有三个空格,单词前后也均有空格) " i am student, you are teacher " , 各个单词首字符大写
- 请实现一个函数,把字符串中的每个空格替换成“%20”
- 【C语言】字符串替换空格:请实现一个函数,把字符串中的每个空格替换成“%20”。
- 【C语言】字符串替换空格:实现一个函数,把字符串里的空格替换成“%20”
- 替换空格:请实现一个函数,把字符串中的每个空格替换成“%20”
- 请实现一个函数,把字符串中的每个空格替换成“%20”。例如输入“We are happy.”,则输出“We%20are%20happy.”。
- 请实现一个函数,把字符串中的每个空格替换成“%20”
- 请实现一个函数,把字符串中的每个空格替换成“%20”,例如输入 “We are Happly。” 则输出“we%20are%20happy。”
- 请实现一个函数,把字符串中的每个空格替换成“%20”。
- 【C语言】【面试题】【笔试题】.字符串替换空格:请实现一个函数,把字符串中的每个空格替换成“%20”。
- 实现一个函数,将一个字符串中的空格替换成“ % 20”