Ask your own question, for FREE!
Computer Science 8 Online
mhchen:

How to find a specific char in a char[] array in C. ```c char fullName[50]; strcpy(fullName,"Bob,Chen"); char firstName[30],lastName[30]; /* I want "Bob" in firstName and "Chen" in lastName */ ``` @Ultrilliam

mhchen:

Update: I'm attempting this solution: https://fresh2refresh.com/c-programming/c-strings/c-strchr-function/

mhchen:

Update: ```c char fullName[60] = "Bob,Chen"; char lastName[30], firstName[30]; char *p; p = strchr (fullName,','); int position = p-fullName; strncpy(firstName,fullName,position+1); printf ("%s\n",firstName); strcpy(lastName,p); printf("%s\n",lastName); ``` Output: ```firstName is "Bob," and lastName is ",Chen"``` Now how do I get rid of the commas...

mhchen:

``` char fullName[60] = "Bob,Chen"; char lastName[30], firstName[30]; char *p; p = strchr (fullName,','); int position = p-fullName; strncpy(firstName,fullName,position); firstName[position] = 0; printf ("%s\n",firstName); strcpy(lastName,p+1); printf("%s\n",lastName); ``` FINALLY WORKED LOL

Ultrilliam:

```c int main() { char fullName[60] = "Bob,Chen"; char lastName[30], firstName[30]; char *p; p = strchr(fullName,','); int position = p-fullName; strncpy(firstName,fullName,position); printf ("%s\n",firstName); strcpy(lastName,p+1); printf("%s\n",lastName); return 0; } ``` Close, but the output of first name is garbled text.

Ultrilliam:

Did we just do the same solution at the same time

mhchen:

That is creepy.....wow

mhchen:

except I had firstName[position] = 0; Otherwise firstName would be "Bob?" and that annoying question-mark in a diamond symbol

Ultrilliam:

Yea... thats what I mean by "Garbled Text" lol

mhchen:

Welp xd it's solved then.

Ultrilliam:

Back to working with JS LOL

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!