Yahoo Clever wird am 4. Mai 2021 (Eastern Time, Zeitzone US-Ostküste) eingestellt. Ab dem 20. April 2021 (Eastern Time) ist die Website von Yahoo Clever nur noch im reinen Lesemodus verfügbar. Andere Yahoo Produkte oder Dienste oder Ihr Yahoo Account sind von diesen Änderungen nicht betroffen. Auf dieser Hilfeseite finden Sie weitere Informationen zur Einstellung von Yahoo Clever und dazu, wie Sie Ihre Daten herunterladen.
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 Antworten
- Anonymvor 1 JahrzehntBeste Antwort
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 5vor 1 Jahrzehnt
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 7vor 1 Jahrzehnt
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