修剪字符串中的空格

问题描述 投票:0回答:7

我知道在Java和C中有几种很好的方法可以做到这一点,但在C++中我似乎找不到一种方法来轻松实现字符串修剪功能。

这是我目前拥有的:

string trim(string& str)
{
    size_t first = str.find_first_not_of(' ');
    size_t last = str.find_last_not_of(' ');
    return str.substr(first, (last-first+1));
}

但是每当我尝试打电话时

trim(myString);

我收到编译器错误

/tmp/ccZZKSEq.o: In function `song::Read(std::basic_ifstream<char, 
std::char_traits<char> >&, std::basic_ifstream<char, std::char_traits<char> >&, char const*, char const*)':
song.cpp:(.text+0x31c): undefined reference to `song::trim(std::string&)'
collect2: error: ld returned 1 exit status

我正在尝试找到一种简单且标准的方法来修剪字符串中的前导和尾随空格而不占用 100 行代码,并且我尝试使用正则表达式,但无法让它正常工作。

我也无法使用Boost。

c++ string whitespace trim
7个回答
43
投票

你的代码没问题。您看到的是链接器问题。

如果您将代码放入单个文件中,如下所示:

#include <iostream>
#include <string>

using namespace std;

string trim(const string& str)
{
    size_t first = str.find_first_not_of(' ');
    if (string::npos == first)
    {
        return str;
    }
    size_t last = str.find_last_not_of(' ');
    return str.substr(first, (last - first + 1));
}

int main() {
    string s = "abc ";
    cout << trim(s);

}

然后执行

g++ test.cc
并运行 a.out,你会看到它有效。

您应该检查包含

trim
函数的文件是否包含在编译过程的链接阶段。


29
投票

您可以这样做:

std::string & trim(std::string & str)
{
   return ltrim(rtrim(str));
}

支持功能实现为:

std::string & ltrim(std::string & str)
{
  auto it2 =  std::find_if( str.begin() , str.end() , [](char ch){ return !std::isspace<char>(ch , std::locale::classic() ) ; } );
  str.erase( str.begin() , it2);
  return str;   
}

std::string & rtrim(std::string & str)
{
  auto it1 =  std::find_if( str.rbegin() , str.rend() , [](char ch){ return !std::isspace<char>(ch , std::locale::classic() ) ; } );
  str.erase( it1.base() , str.end() );
  return str;   
}

一旦你完成了所有这些,你也可以这样写:

std::string trim_copy(std::string const & str)
{
   auto s = str;
   return ltrim(rtrim(s));
}

试试这个


7
投票

我认为如果 str 仅包含空格,则 substr() 会引发异常。

我将其修改为以下代码:

string trim(string& str)
{
    size_t first = str.find_first_not_of(' ');
    if (first == std::string::npos)
        return "";
    size_t last = str.find_last_not_of(' ');
    return str.substr(first, (last-first+1));
}

6
投票

使用正则表达式

#include <regex>
#include <string>

string trim(string s) {
    regex e("^\\s+|\\s+$");   // remove leading and trailing spaces
    return regex_replace(s, e, "");
}

// if you prefer the namespaced version
std::string trim(std::string s) {
    std::regex e("^\\s+|\\s+$"); // remove leading and trailing spaces
    return std::regex_replace(s, e, "");
}

归功于:https://www.regular-expressions.info/examples.html正则表达式


0
投票
#include <vector>
#include <numeric>
#include <sstream>
#include <iterator>

void Trim(std::string& inputString)
{
    std::istringstream stringStream(inputString);
    std::vector<std::string> tokens((std::istream_iterator<std::string>(stringStream)), std::istream_iterator<std::string>());

    inputString = std::accumulate(std::next(tokens.begin()), tokens.end(),
                                 tokens[0], // start with first element
                                 [](std::string a, std::string b) { return a + " " + b; });
}

0
投票

除了@gjha的回答:

inline std::string ltrim_copy(const std::string& str)
{
    auto it = std::find_if(str.cbegin(), str.cend(),
        [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
    return std::string(it, str.cend());
}

inline std::string rtrim_copy(const std::string& str)
{
    auto it = std::find_if(str.crbegin(), str.crend(),
        [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
    return it == str.crend() ? std::string() : std::string(str.cbegin(), ++it.base());
}

inline std::string trim_copy(const std::string& str)
{
    auto it1 = std::find_if(str.cbegin(), str.cend(),
        [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
    if (it1 == str.cend()) {
        return std::string();
    }
    auto it2 = std::find_if(str.crbegin(), str.crend(),
        [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
    return it2 == str.crend() ? std::string(it1, str.cend()) : std::string(it1, ++it2.base());
}

0
投票

带有测试的解决方案

令人有些惊讶的是,这些解决方案都没有提供简单的测试功能来演示其

trim
版本的行为方式。

这是这样一个例程:

void test(std::string const& s)
{
    auto const quote{ '\"' };
    auto const q{ quote + s + quote };
    auto const t{ quote + trim(s) + quote };
    std::streamsize const w{ 6 };
    std::cout << std::left 
        << "s = " << std::setw(w) << q 
        << " : trim(s) = " << std::setw(w) << t 
        << '\n';
}
int main()
{
    for (std::string s : {"", " ", "   ", "a", " a", "a ", " a "})
        test(s);
}

测试已接受的解决方案

当我在 2023 年 8 月 5 日针对已接受的答案运行此代码时,我对它处理完全由空格组成的字符串的方式感到失望。我希望它们被修剪成空字符串。相反,它们原封不动地返回。 if 语句就是原因。

// Accepted solution by @Anthony Kong. Copied on 2023-Aug-05.
using namespace std;
string trim(const string& str)
{
    size_t first = str.find_first_not_of(' ');
    if (string::npos == first)
    {
        return str;
    }
    size_t last = str.find_last_not_of(' ');
    return str.substr(first, (last - first + 1));
}

这是我的测试的输出:

s = ""     : trim(s) = ""
s = " "    : trim(s) = " "
s = "   "  : trim(s) = "   "
s = "a"    : trim(s) = "a"
s = " a"   : trim(s) = "a"
s = "a "   : trim(s) = "a"
s = " a "  : trim(s) = "a"

测试“新的和改进的”版本的trim

为了使其按照我想要的方式工作,我更改了 if 语句。

当我这样做时,我去掉了

using namespace std;
,并将参数名称更改为
s
。你知道,因为我可以。

std::string trim(const std::string& s)
{
    auto const first = s.find_first_not_of(' ');
    if (std::string::npos == first)
        return {};
    auto const last = s.find_last_not_of(' ');
    return s.substr(first, (last - first + 1));
}

现在测试例程产生我喜欢的输出:

s = ""     : trim(s) = ""
s = " "    : trim(s) = ""
s = "   "  : trim(s) = ""
s = "a"    : trim(s) = "a"
s = " a"   : trim(s) = "a"
s = "a "   : trim(s) = "a"
s = " a "  : trim(s) = "a"
© www.soinside.com 2019 - 2024. All rights reserved.