Reputation: 1
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
Upvotes: 0
Views: 95
Reputation: 916
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:
strlen(old_string) + space_count + 1
longLet me know if it's not clear enough, or if you need more precise informations.
Upvotes: 2
Reputation: 67709
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
Upvotes: 1