所以我得到了这样一个字符串:
Hello6World66ABC
我被告知要将字符“6”的单个实例替换为两个星号字符“**”
并且 6 的多个实例是这些字符中的两个 “^^”
(连续数字 6 的任何组合都符合条件。
我试图通过遍历 char *
中的每个字符来做到这一点,然后如果我找到第 6 个字符,我检查下一个字符是否是 6,如果不是,我们有第一种情况,否则我们有第二种情况(多个 6)。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void) {
char * str;
int i;
str = malloc(17);
strcpy(str,"Hello6World66ABC");
for(i=0; i < strlen(str); i++) {
if(str[i] == '6') {
if(str[i+1] != '6') {
char * token = strtok(str,"6");
strcpy(str,token);
strcat(str,"**");
printf("String is now %s\n",str);
token = strtok(NULL,""); /*get the rest of the string*/ /* should be World66ABC */
printf("Rest of the string is %s\n",token);
str = (char *) realloc(str,strlen(str) + strlen(token) + 1);
strcat(str,token);
printf("String is now %s\n",str);
/* should be Hello**World66ABC */
}
else {
/*if the next characters are also (multiple ones in a row) 6's, replace it with two ^^ characters*/
char * token = strtok(str,"6");
token = strtok(NULL,"6");
printf("TOKEN IS %s\n",token);
strcpy(str,token);
strcat(str,"^^");
token = strtok(NULL,""); /*get the rest of the string*/ /* should be World66ABC */
printf("Rest of the string is %s\n",token);
str = (char *) realloc(str,strlen(str) + strlen(token) + 1);
strcat(str,token);
printf("String is now %s\n",str);
}
}
}
free(str);
return 0;
}
根据给出的字符串,我预期的最终字符串应该是:
Hello**World^^ABC
但是,我的 strtok 调用没有按我预期的方式工作。
在第二个 if 语句中,我检查 if (str[i+1] != '6')
,我检查是否只有一个 6,有。
然后我调用 strtok 并打印它之前的所有内容:
它打印:Hello**
哪个是正确的 我将新字符添加到它上面,但是,在我的第二次 strtok 调用中,为了获取字符串的其余部分,它只是不起作用。
而是打印:
"Rest of the string is *"
很明显它没有得到字符串的其余部分,即使我将分隔符设置为空字符串也是如此。
我尝试将分隔符更改为其他字符,但每个字符的输出结果相同。我也在重新分配,因为在第一种情况下字符串变长了。此外,else 语句似乎永远不会运行,即使我清楚地遇到了多个 6 的情况。
我不确定这里哪里出了问题,有什么想法吗?
最佳答案
这是未经测试的,但它显示了总体思路。
strcpy(str,"Hello6World66ABC");
// New string will be at most 2x as long
char *new_str = calloc(strlen(str) * 2 + 1, 1);
int new_str_index = 0;
for (int i = 0; 0 != str[i]; i++) {
// Check for 6
if ('6' == str[i]) {
// Check for 2nd 6
if ('6' == str[i+1]) {
// Add chars
new_str[new_str_index++] = '^';
new_str[new_str_index++] = '^';
// Consume remaining 6s - double check this for off-by-one
while ('6' == str[i+1]) i += 1;
}
else {
// Add chars
new_str[new_str_index++] = '*';
new_str[new_str_index++] = '*';
}
}
// No 6s, just append text
else {
new_str[new_str_index++] = str[i];
}
}
关于c - 使用 strtok 时的意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39858626/