您的位置 首页 > 腾讯云社区

剑指offer--替换空格---AI那点小事

请实现一个函数,将一个字符串中的空格替换成“%20”。 例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

思路: 遍历字符串,遇见“ 后替换成“%20”并把控制下标的变量加3,如果不是则继续,即控制下标的变量加1。

Java代码如下:

public class Solution { public int Find(int start , char c,StringBuffer str){ int index = -1; char[] ch = str.toString().toCharArray(); for ( int i = start ; i < str.length() ; i++){ if ( ch[i] == c){ index = i; break; } } return index; } public String replaceSpace(StringBuffer str) { String s = "%20"; for ( int i = 0 ; i < str.length() ; ){ int index = Find(i, ' ', str); if ( index != -1){ str.replace(index, index+1,s); i = i + 3; continue; }else{ i++; continue; } } return str.toString(); } }

C++代码如下:

class Solution { public: void replaceSpace(char *str,int length) { int oldlength = 0; int newlength = 0; int i = 0; //首先遍历数组计算新数组长度 while(str[i] != ''){ oldlength++; if(str[i] == ' '){ newlength += 3; }else{ newlength++; } i++; } //开始替换 while(oldlength >= 0){ if(str[oldlength] == ' '){ str[newlength--] = '0'; str[newlength--] = '2'; str[newlength--] = '%'; }else{ str[newlength--] = str[oldlength]; } oldlength--; } } };

---来自腾讯云社区的---AI那点小事

关于作者: 瞎采新闻

这里可以显示个人介绍!这里可以显示个人介绍!

热门文章

留言与评论(共有 0 条评论)
   
验证码: