【面试题】剑指Offer-4-替换空格

    xiaoxiao2021-03-25  96

    题目概述

    实现一个函数,可以把字符串的每个空格替换成“ ”.例如输入"We are human",输出"We are human".

    考点

    这道题目考验了面试者对内存覆盖是否存有高度的警惕,只要保持冷静,思考到从后往前的替换方法,就很好解决了

    方法步骤

    1、遍历一遍字符串,找出空格的个数count

    2、将字符串扩容到对应长度

    3、从后往前进行拷贝

    4、根据当前的count计算替换的位置tmp

    遇到需要替换的字符时,用replace进行替换,然后tmp减去对应长度;

    否则直接拷贝到对应位置上;

    5、如此反复直到tmp为0

    代码实现

    #include<iostream> using namespace std; #include<string> #include<assert.h> //替换空格 //src代表被替换的字符 //des是替换的目标字符串 void ReplaceChar(string& str,const char src = ' ', const string& des = " ") { assert(!str.empty()); assert(!des.empty()); //获得需要修改字符串的数量,从而求出拷贝的差值,以及拷贝后字符串的长度 size_t count = 0; for (size_t i = 0; i < str.length(); ++i) { if (str[i] == src) count++; } size_t oldSize = str.length(); size_t tmp = (des.length() - 1)*count; //将string扩容到对应大小 str.resize(oldSize + tmp); //进行拷贝 for (int i = oldSize; i >= 0; i--) { //如果碰到需要修改的字符,则用replace函数进行替换 //如果不是需要修改的字符,则直接往后拷贝到对应的位置上 if (str[i] == src) { //replace(size_t pos,size_t length,const string& s) str.replace(i + tmp - des.length() + 1,des.length(),des); //拷贝后,tmp减去相应的位数 tmp -= (des.length()-1); if (tmp == 0) return; } else { str[i + tmp] = str[i]; } } } void TestReplaceChar() { string s("We are human"); ReplaceChar(s); cout << s << endl; } int main() { TestReplaceChar(); return 0; }

    小结

    合并两个字符串或者数组时,如果从前往后需要挪动很多字符,那么就要考虑从后往前的替换方法

    转载请注明原文地址: https://ju.6miu.com/read-19093.html

    最新回复(0)