最近看书看不下去就刷面试题,决定把字符串有关面试题都写这个文章里
1.实现一个函数在字符串中把空格替换成”%20”
注意是否会发生内存溢出
#include <iostream>
#include <cstring>
using namespace std;
void changeZi(char** buff, int size)
{
int num = 0;//多少个空格
char* tmp2 = new char[size];
strcpy_s(tmp2, size, *buff);
for (int i = 0; i < size; ++i)
{
if (tmp2[i] == ' ')
{
num++;
}
}
if(num = 0)//要考虑没有空格的情况,那么就什么操作也不做
{
return ;
}
char* tmp = new char[size + num * 2];
int j = 0;
for (int i = 0; i < size; ++i)
{
if (tmp2[i] != ' ')
{
tmp[j++] = tmp2[i];
}
else
{
tmp[j++] = '%';
tmp[j++] = '2';
tmp[j++] = '0';
}
}
*buff = new char[size + num * 2];
strcpy_s(*buff, size + num * 2, tmp);
delete[] tmp;
delete[] tmp2;
}
int main()
{
char* buff = "we are happy.";
changeZi(&buff, strlen(buff) + 1);
cout << buff << endl;
return 0;
}
如果是对于已经知晓的,长度足够的数组,我们可以只通过O(n)的复杂度来赋值,一个指针指向计算出新的长度的末尾,一个指针指向原先长度的末尾,然后往前走,这样只需要O(n)就可以在原先数组上面复制成功了。
注意思考问题的完备性测试用例
(1)输入字符串包含空格
(2)输入字符串不包含空格
(3)输入字符串为NULL,因为代码需要求长度,所以如果是空就进不去我的函数,所以算是变相检查
新思想:
在复制字符串时候为了避免移动,我们可以考虑从后向前复制,这样可以大大的增加效率。