![How do I select when to print specific characters in a character array [closed]](https://www.xszz.org/skin/wt/rpic/t12.jpg)
Question:
For my assignment I need to do the following
<ul><li>Ask the user to input their name and save it to a character array</li> <li>Then I need to output the number of characters input by said user</li> <li>Then I have to spell that user's name backwards</li> <li>followed by telling the user which part of the character array contained the space between their first and last name</li> <li>The last thing that I need to do but can't quiet figure out (actually I'm completely lost) is output the user's last name first then first name last (ie John Doe = Doe John);
#include <stdio.h>
#include <string.h>
int main ()
{
printf("Enter your name\n");
char name [25]={'\0'};
char * pch;
fgets(name,sizeof(name),stdin);
printf("You Entered: %s \n", name);
printf("There are %u characters in your name including the space. \n", strlen(name));
char end;
int i;
end = strlen(name) -1;
printf("Your name backwards is");
for (i = end; i >= 0; --i)
{
printf("%c", name [i]);
}
printf("\nLooking for the space in your name \n", name);
pch=strchr(name, ' ');
while (pch!=NULL)
{
printf("Space found at %d\n", pch-name+1);
pch=strchr(pch+1, ' ');
}
}
</li>
</ul>Anyone that knows how to do this Can you please explain what you did so I can learn from you?
Answer1:Since you found the space, cut the string in half there by overwriting it with a '\0'
character:
*pch = '\0';
Then print first the string following where the space was, and then the whole string:
printf("last name: %s\n", pch + 1);
printf("first name: %s\n", name);
This will break somewhat if there are multiple spaces, but you get the idea.
Answer2:You know the index where the space occured(pch
here). Print pch+1
to end
and then from 0
to pch
if you are iterating the string by character.
You already found the location where the space in the name is in the second to last question. Just replace the space with a \0
. Then printf the two strings:
*pch = '\0';
printf("%s %s\n",pch + 1,name);
Answer4:<blockquote>
The last thing that I need to do but can't quiet figure out (actually I'm completely lost) is output the users last name first then first name last (ie John Doe = Doe John);
</blockquote>It is common assignment/interview question of how to reverse an oder of strings in an array. An elegant albeit maybe not the most efficient algorithm would be:
step 1: reverse the array character by character
step 2: reverse each string in-place
Check the answers <a href="https://stackoverflow.com/questions/1009160/reverse-the-ordering-of-words-in-a-string" rel="nofollow">here</a> for more info.