Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.
Trending News
how to extract the last token in C?
I have array of char something like this--->program1|program2|program3|program4|program5
how to get the last token(program5) without using strtok
3 Answers
- Anonymous1 decade agoFavorite Answer
Index into the string maintain last and current index. When current is at a "|" then between last and current is your next word. Change last = current + 1.
When current points to "\0" you are done.
int current = 0, last =0;
while (array[current] != '\0')
{
if (array[current] = '|')
{
token is between array[current]-1 and last
current++;
last=current;
}
else
current++;
}
if (last != current)
then last token is at array[last];
- FrecklefootLv 51 decade ago
Why don't you want to use strtok()? It sounds like a perfect application of it. If you're worried about destroying the original string, make a copy of the original pointer or copy the entire string somewhere. HTH
- cjaLv 71 decade ago
If all you really want is the last token, it's pretty easy (see below). If you want full tokenization functionality without using strtok, it'll be a bit more work.
#include <stdio.h>
#include <string.h>
#define MAX_TOK_LEN 128
#define DELIM '|'
const char *s0 = "one|two|three|four";
const char *s1 = "five";
const char *s2 = "six|";
char tok[MAX_TOK_LEN];
char *lastTok(const char *, char *);
int main(int argc, char *argv[]) {
printf("%s\n",lastTok(s0,tok));
printf("%s\n",lastTok(s1,tok));
printf("%s\n",lastTok(s2,tok));
return 0;
}
char *lastTok(const char *str, char *tok) {
if ((str != NULL) && (tok != NULL)) {
char *p = strrchr(str,DELIM);
p = (p != NULL) ? p+1 : (char *)str;
strcpy(tok,p);
}
return tok;
}
#if 0
Program output:
four
five
#endif