我有一行格式如下:
str="WORD1\tWORD2\tWORD3\tWORD4...";
问题是我需要得到第三个词。
我一直在玩弄 strchr 和 strcpy,但我只是弄得一团糟。
我唯一想做的就是保存在同一个字符串变量 str 中,这样我就可以继续解析直到第三列。
char *p;
p=strchr(str,'\t');
strcpy(str,str,p?);
非常感谢您的帮助。
谢谢!
试试这个,只是一个想法(我没有检查其他字符串):
代码没有给出 first 和 last 的词,它只输出你需要的 \t
括号中的子字符串。:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(){
char* str="WORD1\tWORD2\tWORD3\tWORD4";
char *p1 = NULL;
char *p2 = NULL;
int i = 0, which = 3;
char word[10]={0};
scanf("%d", &which );
p1 = str;
for(i=0 ; (p1 != NULL) && (i < which-1); i++){
p1=strchr(p1 + 1, '\t');
if(p1 +1)
p2=strchr(p1 + 1, '\t');
}
if(p1!=NULL && p2!=NULL){
strncpy(word, p1, p2-p1);
printf("\n %s\n", word);
}
return 1;
}
它的运行方式如下:
$ ./a.out
1
:~$ gcc x.c
:~$ ./a.out
2
WORD2
:~$ ./a.out
3
WORD3
:~$ ./a.out
4
这是你需要的吗?
我是一名优秀的程序员,十分优秀!