C - 对 strtok 切断的位置有问题



基本上对于我的代码,我有变量/键对。当在代码中遇到变量时,函数(包含下面部分行)将替换为其键。例如,如果用户输入字符串"Hello ABC World",并且变量被声明为ABC ="Great Big",则输入字符串将更改为"Hellow Great Big World"。我通过在变量之前和变量之后对字符串的部分进行strtok来实现这一点,然后连接newfirst(变量之前的部分)+变量键+newsecond(变量之后的部分)。在大多数情况下,这效果很好,除非变量位于字符串"Hello World ABC"的末尾。因此,留下我认为是单个字符"",并抛出错误,因为它无法标记剩下的字符。有什么方法可以错误地解决这个问题吗?

           // Place the part of the string before the variable prescence in newfirst
            strcpy(newfirst, strtok(nonVariable[i], myVariables[a].variable));
            // Place the part of the string after the variable prescence in newsecond
            for(c = 0; c < strlen(newsecond); c++)
            {
                if(newsecond[c] == ' ')
                    hasSpaces = 1;
            }
            if(hasSpaces = 0)
            {
                strcpy(newsecond, strtok(NULL, "n"));
            }
            else
            {
                strcpy(newsecond, strtok(NULL, " "));
                strcpy(newsecond, strtok(NULL, "n"));
            }
            // substitute all key values in for their corresponding variables
            strcat(newfirst, " ");
            strcat(newfirst, myVariables[a].key);
            strcat(newfirst, " ");
            strcat(newfirst, newsecond); 
            strcpy(nonVariable[i], newfirst); 

你可以给一个带有几个字符的分隔符字符串来strtok()

ptr = strtok(NULL, " nt");

见人斯特托克

最新更新