问题
For my assignment I need to do the following
- Ask the user to input their name and save it to a character array
- Then I need to output the number of characters input by said user
- Then I have to spell that user's name backwards
- followed by telling the user which part of the character array contained the space between their first and last name
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, ' '); } }
Anyone that knows how to do this Can you please explain what you did so I can learn from you?
回答1:
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.
回答2:
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.
回答3:
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);
回答4:
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);
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 here for more info.
来源:https://stackoverflow.com/questions/19054199/how-do-i-select-when-to-print-specific-characters-in-a-character-array