gpt4 book ai didi

c - 如何在c中用 '%30'替换字符串中的空格

转载 作者:太空宇宙 更新时间:2023-11-04 07:53:30 24 4
gpt4 key购买 nike

如何用 '%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;
}

关于c - 如何在c中用 '%30'替换字符串中的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52220506/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com