如何解决试图从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次。
您可以改为执行类似的操作来删除?
。此代码将返回一个新的malloc分配的字符串,如果该字符串的?
被删除,则最后一个字符将被删除。
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,length + 1);
return word_copy;
}
或者,如果您感到懒惰,也可以将最后一个字符设置为新的空终止符。它实际上会造成1字节的内存泄漏,但这可能是可以接受的损失。由于不需要分配任何新的内存或复制先前的字符串,因此它也应该更快一些。
unsigned int length = strlen(word);
if (length > 0 && word[length - 1] == '?') {
word[length] = 0;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。