gpt4 book ai didi

c - 如何用定界符解析

转载 作者:太空宇宙 更新时间:2023-11-04 03:56:36 27 4
gpt4 key购买 nike

我有一行格式如下:

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

这是你需要的吗?

关于c - 如何用定界符解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15964400/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com