【发布时间】:2015-12-12 18:35:51
【问题描述】:
我尝试制作一个函数,将文本中的每个单词替换为向右移动“k”次的单词。 代码如下所示:
void operation_3(char *string, int k){
int len = 0, i;
int string_len = strlen(string);
char *word;
char s[12] = " .,?!\"'";
char *dup;
dup = strdup(string);
word = strtok(dup, s);
while (word != NULL) {
len = strlen(word);
char *new_word = (char *)malloc(len * sizeof(char));
for (i = 0; i < k; i++) {
new_word = shift_to_right(word);
}
string = replace_word(string, word, new_word);
word = strtok(NULL, s);
}
}
shift_to_right 是:
char *shift_to_right(char *string){
char temp;
int len = strlen(string) - 1;
int i;
for (i = len - 1; i >= 0; i--) {
temp = string[i+1];
string[i+1] = string[i];
string[i] = temp;
}
return string;
}
replace_word 是:
char *replace_word(char *string, char *word, char *new_word) {
int len = strlen(string) + 1;
char *temp = malloc(len * sizeof(char));
int temp_len = 0;
char *found;
while (found = strstr(string, word)) {
if (strlen(found) != strlen(word) || isDelimitator(*(found - 1)) == 1) {
break;
}
memcpy(temp + temp_len, string, found - string);
temp_len = temp_len + found - string;
string = found + strlen(word)
len = len - strlen(word) + strlen(new_word);
temp = realloc(temp, len * sizeof(char));
memcpy(temp + temp_len, new_word, strlen(new_word));
temp_len = temp_len + strlen(new_word);
}
strcpy(temp + temp_len, string);
return temp;
}
而isDelimitator是:
int isDelimitator(char c) {
if(c == ' ' || c == '.' || c == ',' || c == '?' || c == '!' ||
c == '"' || c == '\0' || c == '\'') {
return 0;
}
else return 1;
}
我测试了 shift_to_right、replace_word 和 isDelimitator 并且工作正常。但是最后一个函数 operation_3 没有按预期工作。例如,对于输入:“Hi I am John”,对于 k = 1,输出是:“Hi I am John”。基本上 operation_3 不会修改字符串。有什么建议,请指正?
【问题讨论】:
-
您能否举一个“单词向右移动 'k' 次”的示例,您发布的示例没有告诉我们任何信息,因为输出显然与输入相同。
-
抱歉,我说的不是很准确。对于 word = abcd 和 k = 1,输出应该是 dabc。所以对于:“Hi I am John”和 k = 1 应该是:“iH I manJoh”
-
在您的
replace_word中,您有一个if条件strlen(found) != strlen(word)我认为strstr从string中返回一个指针,从那里子字符串匹配,在这种情况下strlen(found) != strlen(word)总是正确的,除非这个词是string中的最后一个词,所以你在大多数代码中没有做任何事情就打破了循环。 -
如果发现这样的内容,我尝试设置停止条件:当我只需要约翰时,约翰。 Strstr 查找所有子字符串。你有什么解决办法吗?
标签: c string function pointers replace