移除字符串中多余的空格

int rm_extra_spaces(char* input)
{
    int len = strlen(input);
    if (input == NULL || len > MAX_INPUT_LEN) {
        return -1;
    }
    //去除尾部空格
    char* ptr = input + len - 1;
    while (ptr >= input && *ptr == ' ') {
        *ptr = '\0';
        ptr--;
    }
    //去除首部空格
    len = 0;
    ptr = input;
    while (*ptr != '\0' && *ptr == ' ') {
        ptr++;
        len++;
    }
    memmove(input, ptr, strlen(ptr) + 1);
    //去除中间的重复空格
    char* pos = NULL;
    char* tmp = NULL;
    ptr = input;
    do {
        pos = strchr(ptr, ' ');
        if (pos == NULL) {
            break;
        }
        tmp = pos;
        while (*tmp == ' ') {
            tmp++;
        }
        memmove(pos + 1, tmp, strlen(tmp) + 1);
        ptr = pos + 1;
    } while (1);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/tongyishu/p/11682108.html