在这个作业中,我必须在 c 中创建一个 tokeniser 函数,它将一个字符串的内容复制到另一个字符串中,同时删除空格。它返回应该查找下一个标记的位置。
token 是一串字符或单个运算符字符。
在我的尝试中,检测并绕过空格的计数器以某种方式阻止了将内容复制到第一个标记之后的结果字符串中。这是我的代码:
int checkOperators(char str[], char operators[], int i){
int counter = 0;
while(operators[counter]!='\0')
{
if(str[i]==operators[counter]) return 1;
counter++;
}
return 0;
}
int tokenise_ops(char str[], int start, char result[], char operators[]){
int i = start;
int j = start;
while(str[i]==' ' && str[i]!='\0'){
i++;
}
if(checkOperators(str,operators,i)==1)
{
result[j]= str[i];
i++;
return i;
}
while(str[i]!='\0')
{
result[j]= str[i];
i++;
j++;
if(str[i]==' ' || checkOperators(str,operators,i)==1) return i;
}
return -1;
}
int main()
{
char str[]="26.6 * 7.9 + 3";
char result[256];
char operators[]={'+','-','*','/','^','\0'};
int start=0;
start = tokenise_ops(str,start,result,operators);
while ( start != -1 )
{
printf("%s\n", result);
start = tokenise_ops(str, start, result,operators);
}
printf("%s\n", result);
return 0;
}
最佳答案
您的标记化函数可以是:
int tokenise_ops(char str[], int start, char result[], char operators[])
{
int i = start;
int j = 0;
while ((str[i]==' ') && (str[i]!='\0'))
{
i++;
}
while(str[i]!='\0')
{
if(str[i]==' ' || checkOperators(str,operators,i)==1)
{
printf("Test2: %c\n", str[i]);
result[j] = '\0';
return i;
}
else
{
printf("Test: %c\n", str[i]);
result[j] = str[i];
i++;
j++;
}
}
result[j] = '\0';
return -1;
}
j
是result
索引,所以每次调用都要从0
开始- while 循环应该存储与标记不匹配的字符,并在找到标记时以 null 终止结果。
result
在解析整个str
时必须以 null 结尾。
关于c - 寻求调试帮助,为什么这个分词器没有正确复制数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40235367/