简体   繁体   English

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

[英]How to replace spaces in a String with '%30' in c

how to replace spaces in a String with '%30'? 如何用'%30'替换字符串中的空格?

my code is, 我的代码是

int encode_string(char *st)
{
    char *str = st;
    while(*str!='\0')
    {
        if(*str==' ')
        {
            *str="%30";
        }
        str++;
    }
    printf("\n%s",st);
    return 0;
}

it does not replacing the spaces with '%30' as it has more than 1 characters. 它不能用'%30'代替空格,因为它有超过1个字符。

I am able to replace a single literal in a string but not with multiple chars. 我可以用字符串替换单个文字,但不能用多个字符替换。

how to do this? 这个怎么做?

please help 请帮忙

any help would be appriciated 任何帮助都会得到帮助

thank you 谢谢

There is no built in function in c standard to replace a string. c标准中没有内置函数来替换字符串。 You can use custom function as below. 您可以如下使用自定义功能。

 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;
}

The following does the job. 以下是工作。 Because inserting "%30" increases the string length, you must allocate a new string. 由于插入"%30"增加字符串长度,因此必须分配新的字符串。

char *encode_string(char *st)
{
    char *newstr, *tmpstr, *str = st;
    int nspaces= 0, len= 0;
    while(*str!='\0')
    {
        if(*str==' ') nspaces++;
        len++; str++;
    }
    if ((newstr= tmpstr= malloc(len+2*nspaces+1))==0) return 0;
    str= st;
    while(*str!='\0')
    {
        if(*str==' ')
        {
            *tmpstr++= '%';
            *tmpstr++= '3';
            *tmpstr++= '0';
        }
        else *tmpstr++= *str;
        str++;
    }
    *tmpstr = '\0';
    printf("\n%s",newstr);
    return newstr;
}

A bit more universal. 更加通用。 if you pass NULL as a destination buffer it will allocate the memory for you. 如果将NULL作为目标缓冲区传递,它将为您分配内存。 Replaces any char with any string. 用任何字符串替换任何字符。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

inline size_t countchars(const char *str, const char ch)
{
    size_t count = 0;

    while(*str)
    {
        count += *str++ == ch;
    }
    return count;
}

char *replacecs(const char *src, char *dest, char ch, const char *repl)
{
    char *savedptr;
    size_t len = strlen(repl);

    if(dest == NULL)
    {
        dest = malloc(strlen(src) + countchars(src, ch) * (len - 1) + 1);
    }

    savedptr = dest;

    if(dest)
    {
        while(*src)
        {
            if(*src == ch)
            {
                strcpy(dest, repl);
                dest += len;
                src++;
            }
            else
            {
                *dest++ = *src++;
            }
        }
        *dest = 0;
    }
    return savedptr;
}

int main()
{
    char dest[100];
    char *d;

    printf("%s\n", replacecs("Hello  World   Some  Tests ", dest, ' ', "%30"));
    printf("%s\n", (d = replacecs(" Dynamic allocation Hello  World   Some  Tests ", NULL, ' ', "%30")));
    free(d);
    return 0;
}

If the only desired result is to output the new string, as shown in the question, and not to create a new string in memory for further work, then the following suffices. 如果唯一希望的结果是输出新字符串(如问题所示),而不是在内存中创建新字符串以进行进一步的工作,则满足以下条件。

int encode_string(char *st)
{
    putchar('\n');
    while (*st)
    {
        if (*st == ' ')
        {
            putchar('%');
            putchar('2'); // See note below.
            putchar('0');
            // ((One may also use one fwrite instead of three putchar.)
        }
        else
            putchar(*st);
        st++;
    }
    return ferror(stdout);
}

Although the question requests “%30” as a replacement, I suspect this is an error, as the hexadecimal for the ASCII code for space is “20”, and replacing spaces with “%20” is a common substitution for encoding URLs, whereas “%30” is not. 尽管该问题要求替换“%30”,但我怀疑这是一个错误,因为空格的ASCII码的十六进制为“ 20”,而用“%20”替换空格是编码URL的常见替换,而“%30”不是。

Note that it is usually preferred to terminate output lines with \\n rather than to leave them dangling, but this code reproduces the behavior suggested in the question, which writes \\n before the line. 请注意,通常最好用\\n终止输出行,而不是使其悬空,但是此代码重现了问题中建议的行为,该问题在行之前写\\n

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM