gpt4 book ai didi

c - 如何将标记化字符串存储到 C 中的数组中

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

在我的程序中,我读取了一些包含字符串“y'”和“y''”的文本,我想将其存储到名为 lhs[ 100],其余文本进入 rhs[100]。

我该怎么做?我一直在决定它是否适用于 strstr()strcpy()

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

int main() {
FILE *fin;
fin = fopen("diffeq.txt", "r");
char line[100];
char split[] = " +-";
char* token;
char lhs[100];
char rhs[100];
int i = 0;

while (fgets(line, sizeof(line), fin) != NULL)
{
for (token = strtok(line, split); token; token = strtok(NULL, split))
{
// I need to find from the token the string "y'" and "y''"
// and store them into array "lhs[100]" and the rest of the
// contents stored into "rhs[100]"
}
}
fclose(fin);
return 0;
}

最佳答案

此代码正在处理示例文本。我测试过,效果很好。所以你应该添加 read file to text 语句。另外,如果您想在标记之间添加空格,请从 //token[j++] = ' '; 中删除注释符号:

#include <stdio.h>
#include <string.h>
int main() {
char text[] = "this is a y' sample y'' text y ynot?";
int len = strlen(text);
char token[50];
char lhs[100];
char rhs[100];
int state = 0;
int i, j = 0;
token[0] = '\0';
lhs[0] = '\0';
rhs[0] = '\0';
printf("\nlen: %d", len);
for (i = 0; i < len; i++)
switch (text[i]) {
case ' ':
case '+':
case '-':
//token[j++] = ' ';
token[j] = '\0';
//printf("\ntoken> %s", token);
// separator is seen, check the token
if (state == 2 || state == 3)
// token is "y'" or "y''"
strcat(lhs, token);
else
// other token detected
strcat(rhs, token);
state = 0;
j = 0;
break;
case 'y':
token[j++] = text[i];
if (state == 0)
// first 'y' is detected
state = 1;
else
state = 0;
break;
case '\'':
token[j++] = text[i];
if (state == 1)
// we had token=="y" so now we have token=="y'"
state = 2;
else if (state == 2)
// we had token=="y'" so now we have token=="y''"
state = 3;
else state = 0;
break;
default:
token[j++] = text[i];
state = 0;
break;
}
// check token detection condition for last token
if (state == 2 || state == 3)
strcat(lhs, token);
else
strcat(rhs, token);

printf("\n\nlhs> %s\nrhs> %s", lhs, rhs);
}

关于c - 如何将标记化字符串存储到 C 中的数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39928602/

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