在我的程序中,我读取了一些包含字符串“ 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);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句