当前位置:首页 C++ > 正文

c++删除开始和结尾处的空格,并将中间的多个连续的空格合并成一个

作者:野牛程序员:2023-12-04 20:20:12 C++阅读 2128


给定字符串(ASCII码0-255)数组,请在不开辟额外空间的情况下删除开始和结尾处的空格,并将中间的多个连续的空格合并成一个。例如:” i    am      a     little        boy. “,变成” i am a little boy”,C++语言实现函数输入输岀:

#include <iostream>
#include <cstring>

void trimAndReduceSpaces(char* str) {
    // Trim leading spaces
    int start = 0;
    while (str[start] == ' ') {
        start++;
    }

    // Trim trailing spaces
    int end = strlen(str) - 1;
    while (end >= 0 && str[end] == ' ') {
        end--;
    }

    // Shift characters to remove leading spaces
    for (int i = 0; i <= end - start; i++) {
        str[i] = str[i + start];
    }

    // Null-terminate the new string
    str[end - start + 1] = '\\0';

    // Reduce multiple consecutive spaces to a single space
    int currentIndex = 0;
    bool previousSpace = false;

    for (int i = 0; i <= end - start; i++) {
        if (str[i] != ' ') {
            str[currentIndex] = str[i];
            currentIndex++;
            previousSpace = false;
        } else if (!previousSpace) {
            str[currentIndex] = ' ';
            currentIndex++;
            previousSpace = true;
        }
    }

    // Null-terminate the final string
    str[currentIndex] = '\\0';
}

int main() {
    char input[] = "  i am a   little boy.  ";
    trimAndReduceSpaces(input);
    std::cout << input << std::endl;

    return 0;
}


野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892
野牛程序员教少儿编程与信息学竞赛-微信|电话:15892516892
相关推荐

最新推荐

热门点击