LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   how to print the first character in a string using strtok (https://www.linuxquestions.org/questions/programming-9/how-to-print-the-first-character-in-a-string-using-strtok-285112/)

its_godzilla 02-01-2005 07:30 PM

how to print the first character in a string using strtok
 
I need help with a program to pull the first character out of a string I read in. I'm using strtok to get the first name and last name separated by a pipe " | " here is my while loop.


while (fgets(buffer,100,stin) != NULL)
{
token[0] = strtok(string, " | "); // gets the first name
token[1] = strtok(NULL, " | "); // gets the last name


Basically I need to print out the first initial and last name .....
Any ideas????

itsme86 02-01-2005 07:57 PM

If you're sure the pipe will be there I'd just do this:
Code:

printf("%c %s\n", string[0], strchr(string, '|')+1);

its_godzilla 02-01-2005 08:30 PM

Thats not going to work the name comes in like this -----> Bob|Smith|
I need to be able to print BSmith. I need to find out if the strok will let me somehow pull the first char out of token[0] which is the first name = Bob.

its_godzilla 02-01-2005 09:14 PM

Can anyone else give some input????

itsme86 02-02-2005 02:17 AM

Here's a couple of different ways to do it:
Code:

#include <stdio.h>
#include <string.h>

int main(void)
{
  char str[50] = "Bob|Smith|";
  char *s = str;
  char *p;

  p = strtok(s, "|");
  printf("%c", *p);
  p = strtok(NULL, "|");
  printf("%s\n", p);

  return 0;
}

Code:

#include <stdio.h>
#include <string.h>

int main(void)
{
  char str[50] = "Bob|Smith|";
  char *p;

  printf("%c", *str);
  p = strchr(str, '|')+1;
  *strchr(p, '|') = '\0';
  printf("%s\n", p);

  return 0;
}


its_godzilla 02-02-2005 10:22 AM

Thanks for your help I know have it up and running :D :D :D


All times are GMT -5. The time now is 05:54 AM.