剑指Offer-- 替换空格
题目描述
请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
class Solution { public: void replaceSpace(char *str,int length) { int i = 0,count = 0,ncount = 0,bcount =0; // length 为字符数组的总容量 if (str == nullptr || length <= 0) return; // 如果为空字符串或者长度小于等于0,则返回 while ( *(str + i) != '\0') // 尤其注意这个反斜杠的方向 { if ( *(str + i) == ' ') { bcount++; // 首先遍历整个数组找出含有的空格数存入bcount中 } i++; // 控制循环变量 count++; // 计算出实际的字符的长度 } ncount = count + bcount * 2; // 替换后新的字符数组的长度 if ( ncount > length) return; // 如果新的长度大于总容量,则说明装不下,返回 int indexofnew = ncount; int indexofori = count; while (indexofori >= 0 && indexofnew > indexofori) { if ( *( str + indexofori) == ' ') { //若碰到空格应进行的处理 *(str + indexofnew) = '0'; indexofnew--; *(str + indexofnew) = '2'; indexofnew--; *(str + indexofnew) = '%'; indexofnew--; } else // 若不碰到空格则把前一个指针指向的内容赋给后一个指针指向的内存 { *(str + indexofnew) = *(str + indexofori); indexofnew--; } indexofori--; } } };
思路二:
java中的函数
public class Solution { public String replaceSpace(StringBuffer str) { return str.toString().replaceAll("\\s", "%20"); } }