Home > other >  Putting a space after period using C
Putting a space after period using C

Time:12-27

I have an assignment like the codes must capitilize the first letter after period and put a space. I wrote a function like that which capitalize the first letter after period.

for (i = 0; str[i] != '\0'; i  )
{
    if (i == 0)
    {
        if ((str[i] >= 'a' && str[i] <= 'z'))
            str[i] = str[i] - 32;
        continue;
    }
    if (str[i] == '.' || str[i] == '!' || str[i] == '?')
    {
          i;
        if (str[i] >= 'a' && str[i] <= 'z')
        {
            str[i] = str[i] - 32;
            continue;
        }
    }
    else
    {
        if (str[i] >= 'A' && str[i] <= 'Z')
            str[i] = str[i]   32;
    }
}

But I couldn't do the putting space part can someone help me pls

CodePudding user response:

Adding spaces in your string means you're final string will contain more characters than the original one. Thus you'll need to allocate memory, using malloc.

What you can do is:

  • Get the period count in your string
  • Deduce the number of spaces you'll have to add
  • Allocate a new string that is strlen(old_string) space_count 1 long
  • Finally iterate through your old string, copying / modifying each character you want to, and adding a space in the new string when needed

Let me know if it's not clear enough, or if you need more precise informations.

CodePudding user response:

  1. Do not use magic numbers. Use standard functions instead.
  2. passed string has to be modifiable and has enough room to accommodate new spaces.

The function below adds space after characters listed in the after string. If there is a blank space after this character it does not and skips all the blank spaces, then capitalize the first non-blank character. It does not add space if the character listed in after is the last in the string.

char *addSpaceAndCapitalizeAfter(char *str, const char *after)
{
    char *wrk = str;
    if(str && after)
    {
        while(*str)
        {
            if(strchr(after, *str))
            {
                if(str[1] && !isblank((unsigned char)str[1]) && str[2])
                {
                    memmove(str   2, str   1, strlen(str)   1);
                    str[1] = ' ';
                    str  ;
                }
                str  ;
                while(*str && isblank((unsigned char)*str)) str  ;
                if(*str) *str = toupper((unsigned char)*str);
            }
            else
            {
                str  ;
            }
        }
    }
    return wrk;
}


int main(void)
{
    char str[100] = ",test,string,      some, words,";

    printf("`%s`\n", addSpaceAndCapitalizeAfter(str, ","));
}

https://godbolt.org/z/ecq1zxqYW

  •  Tags:  
  • c
  • Related