0

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

Shubham Naphade
  • 49
  • 3
  • 10
  • 2
    In C, strings are arrays of single characters ('char'). "%30" itself is a string, and you cannot set a char to a string. C does not have string-replacement functionality built-in, but you could look up custom implementations e.g. [this](https://stackoverflow.com/questions/779875/what-is-the-function-to-replace-string-in-c). – meowgoesthedog Sep 07 '18 at 10:26
  • 2
    you need to allocate a new buffer st_dest, and copy each char from st to st_dest. For spaces, copy "%30". – user803422 Sep 07 '18 at 10:27
  • You need to create a new buffer for this because when you replace a single character with additional two you going to overwrite or overflow the current buffer – M. Sol Sep 07 '18 at 10:27
  • Possible duplicate of [What is the function to replace string in C?](https://stackoverflow.com/questions/779875/what-is-the-function-to-replace-string-in-c) – hellow Sep 07 '18 at 10:36
  • 3
    I'm guessing you want to replace with `%20`, not `%30`. – Steve Summit Sep 07 '18 at 11:02

4 Answers4

2

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;
}
Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
KBlr
  • 312
  • 1
  • 11
  • 1
    You do not need "+numOfSpace*3", but "+numOfSpace*2", as the original space is counted in strlen(str). – user803422 Sep 07 '18 at 11:14
  • @user803422 Yes, modified accordingly – KBlr Sep 07 '18 at 11:15
  • 1
    your function does not return to the caller the new string so it is useless and causes the memory leak. – 0___________ Sep 07 '18 at 11:32
  • It is not known there is any reason to return the new string to the caller as the question shows the new string being written to the output, and that may be the only result desired. Likely either the new string should be written to output and no new string should be allocated at all (the new string should be written on the fly, with no buffer for it) or the new string should be returned in a buffer without writing it to output. – Eric Postpischil Sep 07 '18 at 11:35
  • @EricPostpischil the question is clear: `how to replace spaces in a String with '%30'?` – 0___________ Sep 07 '18 at 11:44
  • @P__J__: A program that reads input and writes output with the spaces replaced both conforms to that description and matches the code shown in the question. – Eric Postpischil Sep 07 '18 at 11:46
  • @EricPostpischil output != replace in the string – 0___________ Sep 07 '18 at 11:47
  • @P__J__: Yes, the replacement string desired may be a string that appears in output and that does not appear in memory. E.g., Unix has many programs described as filters, whose entire purposes are to produce output text that is the result of various manipulations performed on input text. – Eric Postpischil Sep 07 '18 at 11:49
  • @EricPostpischil we do not discuss unix programs only the particular question. – 0___________ Sep 07 '18 at 11:50
  • @P__J__: I do discuss Unix programs, as the example of language used in describing them serves to illustrate how language is used in discussing programs. – Eric Postpischil Sep 07 '18 at 11:54
  • The code ought to either return the new buffer to the caller or should only write the string to output and not allocate memory. – Eric Postpischil Sep 07 '18 at 11:56
  • @EricPostpischil I fully agree. It's a no-sense to waste CPU allocating unnecessary memory. Also that memory is not freed on output, menaing some confusion about its use: return it or not? Or something alike. – Frankie_C Jun 26 '19 at 16:08
1

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;
}
Paul Ogilvie
  • 25,048
  • 4
  • 23
  • 41
0

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;
}
0___________
  • 60,014
  • 4
  • 34
  • 74
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.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312