c++ - 删除 C++ 中的多余空格

标签 c++ string algorithm

我尝试编写一个脚本来删除多余的空格,但我没能完成它。

基本上我想将 abc sssd g g sdg gg gf 转换为 abc sssd g g sdg gg gf

在 PHP 或 C# 等语言中,这将非常容易,但在 C++ 中则不然,我明白了。这是我的代码:

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <cstring>
#include <unistd.h>
#include <string.h>

char* trim3(char* s) {
    int l = strlen(s);

    while(isspace(s[l - 1])) --l;
    while(* s && isspace(* s)) ++s, --l;

    return strndup(s, l);
}

char *str_replace(char * t1, char * t2, char * t6)
{
    char*t4;
    char*t5=(char *)malloc(10);
    memset(t5, 0, 10);
    while(strstr(t6,t1))
    {
        t4=strstr(t6,t1);
        strncpy(t5+strlen(t5),t6,t4-t6);
        strcat(t5,t2);
        t4+=strlen(t1);
        t6=t4;
    }

    return strcat(t5,t4);
}

void remove_extra_whitespaces(char* input,char* output)
{
    char* inputPtr = input; // init inputPtr always at the last moment.
    int spacecount = 0;
    while(*inputPtr != '\0')
    {
        char* substr;
        strncpy(substr, inputPtr+0, 1);

        if(substr == " ")
        {
            spacecount++;
        }
        else
        {
            spacecount = 0;
        }

        printf("[%p] -> %d\n",*substr,spacecount);

        // Assume the string last with \0
        // some code
        inputPtr++; // After "some code" (instead of what you wrote).
    }   
}

int main(int argc, char **argv)
{
    printf("testing 2 ..\n");

    char input[0x255] = "asfa sas    f f dgdgd  dg   ggg";
    char output[0x255] = "NO_OUTPUT_YET";
    remove_extra_whitespaces(input,output);

    return 1;
}

它不起作用。我尝试了几种方法。我要做的是逐个字母地迭代字符串并将其转储到另一个字符串中,只要一行中只有一个空格即可;如果有两个空格,则不要将第二个字符写入新字符串。

我该如何解决这个问题?

最佳答案

已经有很多不错的解决方案。我建议您基于专用 <algorithm> 的替代方案旨在避免连续重复: unique_copy() :

void remove_extra_whitespaces(const string &input, string &output)
{
    output.clear();  // unless you want to add at the end of existing sring...
    unique_copy (input.begin(), input.end(), back_insert_iterator<string>(output),
                                     [](char a,char b){ return isspace(a) && isspace(b);});  
    cout << output<<endl; 
}

这是一个 live demo 请注意,我从 c 样式字符串更改为更安全、更强大的 C++ 字符串。

编辑:如果您的代码需要保留 c 风格的字符串,您可以使用几乎相同的代码,但使用指针而不是迭代器。这就是 C++ 的魔力。这里是 another live demo .

关于c++ - 删除 C++ 中的多余空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35301432/

相关文章:

c++ - 自定义 wxWidgets 小部件中彼此相邻的两个按钮

c# - 带字符串的 Switch 语句 C#

algorithm - 二分图的两个子集之间的边数

c++ - 如何在 C++ 中将一列数字与不同长度的字符串行分开?

c++ - 将标准函数对象转换回仿函数结构

c# - 什么是 php 中的 tinytext 以及 tinytext 和 string 之间的区别是什么?

algorithm - 找到方法测试矩阵(数学问题)解释的有效方法

python - 如何通过替换 python 中的 for 循环来减少算法的执行时间

c++ - [[nodiscard]] 属性 : By default? 的指南仅在某些误用检测的情况下?

python - 如何使用 python 匹配文本文件中的单词?