题解 | #替换空格#
替换空格
https://www.nowcoder.com/practice/0e26e5551f2b489b9f58bc83aa4b6c68
#include <iostream> #include <string> using namespace std; class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @return string字符串 */ string replaceSpace(string s) { // write code here int length = s.length(); char* array = new char[length*3]; int index=0; for(int i=0;i<length;i++){ if(s[i]==' '){ array[index]='%'; index++; array[index]='2'; index++; array[index]='0'; index++; } else { array[index]=s[i]; index++; } } string output(array); cout <<output<< endl; delete[] array; return output; } };
在堆上新建一个三倍输入大小的动态字符数组array,然后遍历输入字符串,判断当前字符是否为空格,若是, 则将array索引为index,index+1, index+2的值赋值为%,2,0,若不是空格,则将array[index]赋值为此字符,最后清除array内存。