[英]Trying to delete a specific character from a string in C?
我试图从字符串的末尾删除一个特定的字符 (?) 并返回一个指向字符串的指针,但目前它根本没有删除它。 我究竟做错了什么? 有没有更好的方法来解决它?
char * word_copy = malloc(strlen(word)+1);
strcpy(word_copy, word);
int length = strlen(word_copy);
int i = 0;
int j = 0;
for (i = 0; word_copy[i] != '\0'; i++) {
if (word_copy[length - 1] == '?' && i == length - 1){
break;
}
}
for (int j = i; word_copy[j] != '\0'; j++) {
word_copy[j] = word_copy[j+1];
}
word = strdup(word_copy);
我立即发现了一些问题。
第一个 for 循环什么都不做。 它实际上并不依赖于i
因此可以用单个 if 语句替换它。
if (word_copy[length - 1] == '?') {
i = length - 1;
} else {
i = length + 1;
}
第二个 for 循环也用作 if 语句,因为它从字符串的末尾开始并且只能运行 0 或 1 次。
你可以做这样的事情来删除?
. 此代码将返回一个新的 malloced 字符串,如果它的?
.
char *remove_question_mark(char *word) {
unsigned int length = strlen(word);
if (length == 0) {
return calloc(1, 1);
}
if (word[length - 1] == '?') {
char *word_copy = malloc(length);
// Copy up to '?' and put null terminator
memcpy(word_copy, word, length - 1);
word_copy[length - 1] = 0;
return word_copy;
}
char *word_copy = malloc(length + 1);
memcpy(word_copy, word, length + 1);
return word_copy;
}
或者,如果您感到懒惰,也可以将最后一个字符设为新的空终止符。 它本质上会造成 1 字节的内存泄漏,但这可能是可以接受的损失。 它也应该快一点,因为它不需要分配任何新内存或复制前一个字符串。
unsigned int length = strlen(word);
if (length > 0 && word[length - 1] == '?') {
word[length] = 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.