简体   繁体   English

试图从 C 中的字符串中删除特定字符?

[英]Trying to delete a specific character from a string in C?

I'm trying to delete a specific character (?) from the end of a string and return a pointer to a string, but it's not removing it at all at the moment.我试图从字符串的末尾删除一个特定的字符 (?) 并返回一个指向字符串的指针,但目前它根本没有删除它。 What am I doing wrong?我究竟做错了什么? Is there a better way to go about it?有没有更好的方法来解决它?

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);

I'm immediately seeing a couple of problems.我立即发现了一些问题。

The first for loop does nothing.第一个 for 循环什么都不做。 It doesn't actually depend on i so it could be replaced with a single if statement.它实际上并不依赖于i因此可以用单个 if 语句替换它。

if (word_copy[length - 1] == '?') {
    i = length - 1;
} else {
    i = length + 1;
}

The second for loop also acts as an if statement since it starts at the end of the string and can only ever run 0 or 1 times.第二个 for 循环也用作 if 语句,因为它从字符串的末尾开始并且只能运行 0 或 1 次。

You could instead do something like this to remove the ?你可以做这样的事情来删除? . . This code will return a new malloced string with the last character removed if its ?此代码将返回一个新的 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;
}

Or if you are feeling lazy, you could also just make the last character the new null terminator instead.或者,如果您感到懒惰,也可以将最后一个字符设为新的空终止符。 Its essentially creates a memory leak of 1 byte, but that may be an acceptable loss.它本质上会造成 1 字节的内存泄漏,但这可能是可以接受的损失。 It should also be a fair bit faster since it doesn't need to allocate any new memory or copy the previous string.它也应该快一点,因为它不需要分配任何新内存或复制前一个字符串。

unsigned int length = strlen(word);

if (length > 0 && word[length - 1] == '?') {
    word[length] = 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM