本博客分享关于如何替换字符串中的空格算法和求字符串最后一个单词的长度。
一、替换字符串中的空格
例题:
请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
实现函数
基本思想:
替换空格为特定的字符串,首先得知道需要替换的字符串里的空格数目numblank,和总的字符数目count,然后得出替换后的字符串长度,如果它比字符数组空间大,那么返回,(it’s obvious that the space isn’t enough for replacing,huh?),因为是替换,所以肯定要在原来字符串的空间上进行,所以只能从后往前copy(否则就会覆盖数据)。
代码如下:
void replaceSpace(char *str, int length)
{
if (str == NULL || length <= 0)
{
return;
}
int count = 0;//原来字符串中字符数目
int i = 0;
int numblank = 0;//空格数
while (str[i]!='\0')
{
++count;
if (str[i] == ' ')
{
++numblank;
}
++i;
}
int newlen = count+numblank*2;
if (newlen > length)
{
return;//容量不够
}
int index = count;
int newindex = newlen;//下标
while (index >= 0&& newindex>index)
{
if (str[index] == ' ')
{
str[newindex--] = '0';
str[newindex--] = '2';
str[newindex--] = '%';
}
else
{
str[newindex--] = str[index];
}
--index;
}
}
int main()
{
char str[32] = "hello you are what";
replaceSpace(str, 32);
cout << str << endl;
system("pause");
return 0;
}
二、
求字符串最后一个单词的长度
从字符串末尾开始,如果它不是空格,count++,如果遇到空格停止计数,最后返回count。
int Getlen(const string& str)
{
int n = str.size();
if (n>5000)
{
cout << "string is too long" << endl;
return 0;
}
int count = 0;
for (int i = n-1; i >= 0; --i)
{
if (str[i] == ' ')
{
break;
}
else{
count++;
}
}
return count;
}
int main()
{
string str = "ABSIB T";
int sz = str.size();
cout << sz << endl;
cout << Getlen(str) << endl;
system("pause");
return 0;
}