如何用 '%30' 替换字符串中的空格?
我的代码是,
int encode_string(char *st)
{
char *str = st;
while(*str!='\0')
{
if(*str==' ')
{
*str="%30";
}
str++;
}
printf("\n%s",st);
return 0;
}
它不会用“%30”替换空格,因为它有超过 1 个字符。
我能够替换字符串中的单个文字,但不能替换为多个字符。
如何做到这一点?
请帮忙
我们将不胜感激
谢谢
c
标准中没有内置函数来替换字符串。您可以使用如下自定义函数。
int encode_string(char *str)
{
size_t numOfSpace = 0;
for (size_t i=0;str[i]!='\0';i++)
{
if(str[i] == ' ')
numOfSpace++;
}
char *output = malloc(i+numOfSpace*2+1);
if(output == NULL) return -1;
size_t k = 0;
while(*str !='\0')
{
if(*str == ' ')
{
output[k++] = '%';
output[k++] = '3'
output[k++] = '0';
}
else
{
output[k++] = *str;
}
str++;
}
output[k] = '\0';
printf("\n%s\n",output);
return 0;
}
我是一名优秀的程序员,十分优秀!