Reputation: 1380
I'm currently studying C, if this question seems an easy one or a newbie ones, then you know why. Also I already searched here on SO before posting this question. It seems that there are a lot of them but they are not about C, instead Java, php and others.
I'm working on a simple program that has to transform the first char of every word uppercase. For example if the input is :
hello my name is claudio
the output would be
Hello My Name Is Claudio
This is what I coded so far :
#include <stdio.h>
#include <string.h>
int main(void){
char sentence[21] = {'\0'}, sentence2[21] = {'\0'}, *token = NULL;
fgets(sentence,21,stdin);
token = strtok(sentence," ");
while(token != NULL)
{
*token = toupper(token[0]);
strcat(sentence2,token);
token = strtok(NULL," ");
}
puts(sentence2);
return 0;
}
The output is :
MyNameIsClaudio
Obviously that's not what I was expecting, as explained above. I thought that I would have been able to solve the problem simply adding a space like that:
token[strlen(token)+1] = ' ';
strcat(sentence2,token);
But again, the output is not the one expected :
MyAmeSLaudio
Hence, to achieve the desired result I tried :
null_char = strrchr(token,'\0');
*null_char = ' ';
But neither this seems to be the right way. Currently I'm am on a dead end. Can somebody give me a hint on how I can accomplish what I'm trying to do?
Upvotes: 3
Views: 95
Reputation: 154335
Alternative: walk the array
strtok()
looses the space delimiters. This approach maintains groups of spaces.
Walk through the sentence[]
array and for each letter after a space, insure it is uppercase.
fgets(sentence1, sizeof sentence1, stdin);
int precious_space = 1;
size_t len = strlen(sentence1);
for (size_t i = 0; i <= len; i++) {
sentence2[i] = previous_space ? toupper((unsigned char) sentence1[i]) : sentence1[i];
precious_space = sentence1[i] == ' ';
}
fputs(sentence2, stdout);
Alternative loop. See @l3x
size_t i
for (i = 0; sentence1[i]; i++) {
sentence2[i] = previous_space ? toupper((unsigned char) sentence1[i]) : sentence1[i];
precious_space = sentence1[i] == ' ';
}
sentence2[i] = '\0';
Upvotes: 3
Reputation: 224387
You just need to concatenate a space after concatenating the converted string:
strcat(sentence2,token);
strcat(sentence2," ");
Upvotes: 3
Reputation: 3688
You could just add this line to put the spaces back in
while(token != NULL)
{
*token = toupper(token[0]);
strcat(sentence2,token);
token = strtok(NULL," ");
if (token)
strcat(sentence2, " ");
}
Upvotes: 0