字符串替换空格:实现一个函数使字符串中每个空格替换成%20,例:输入we are happy,输出we%20are%20happy
#include <stdio.h>
#include<stdlib.h>
#include<string.h>
#include <assert.h>
void replace_black(char *str)
{
assert(str);
int black = 0;
int oldlen = strlen(str);//字符串长度
int newlen = 0;
char *tmp = str;
while (*tmp)/遍历
{
if (*tmp == ‘ ‘)
black++;//计算空格符数量
tmp++;
}
newlen = oldlen + 2 * black;
while (oldlen < newlen)//从后往前依次移动,当相等时替换完成
{
if (str[oldlen] != ‘ ‘)
{
str[newlen--] = str[oldlen--];
}
else
{
str[newlen--] = ‘0‘;
str[newlen--] = ‘2‘;
str[newlen--] = ‘%‘;
oldlen--;
}
}
}
int main()
{
char p[20] = "we are happy";
replace_black(p);
printf("%s\n", p);
system("pause");
return 0;
}关于strlen求字符串长度
//数组:
int strlen(char *s)//数组名为数组首元素地址
{
int n=0;
for(n=0;*s!=‘\0‘;s++)
n++;
return 0;
}//指针:
int strlen(char *s)
{
char *p=s;
while(*p!=‘\0‘)
p++;
return p-s;
}在用strlen时注意,它的返回类型为无符号数。
本文出自 “无以伦比的暖阳” 博客,请务必保留此出处http://10797127.blog.51cto.com/10787127/1713323
原文:http://10797127.blog.51cto.com/10787127/1713323