简体   繁体   中英

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

how to replace spaces in a String with '%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.

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. 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.

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. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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