c++ 删除字符串中的空格

rbl8hiat  于 2023-08-09  发布在  其他
关注(0)|答案(7)|浏览(86)

我知道在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。

3b6akqbq

3b6akqbq1#

你的代码很好。你看到的是一个链接器问题。
如果你把你的代码放在一个像这样的文件中:

#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函数的文件是否包含在编译过程的链接阶段中。

yvt65v4c

yvt65v4c2#

以下是您可以做到的方法:

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


试试这个

idfiyjo8

idfiyjo83#

我认为如果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));
}

字符串

yshpjwxd

yshpjwxd4#

使用正则表达式

#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用于正则表达式
正如@o_oTurtle提到的-正则表达式非常慢。
另一种方法包括额外的空白字符:

std::string trim(const std::string& str, const std::string REMOVE = " \n\r\t")
{
    size_t first = str.find_first_not_of(REMOVE);
    if (std::string::npos == first)
    {
        return str;
    }
    size_t last = str.find_last_not_of(REMOVE);
    return str.substr(first, (last - first + 1));
}

zqry0prt

zqry0prt5#

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

字符串

iqih9akk

iqih9akk6#

除了@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());
}

字符串

ar5n3qh5

ar5n3qh57#

带测试的解决方案

有些令人惊讶的是,这里的答案都没有提供一个测试函数来演示trim在极端情况下的行为。空字符串和完全由空格组成的字符串都很麻烦。
下面是这样一个函数:

#include <iomanip>
#include <iostream>
#include <string>

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-Aug-05对公认的答案运行这个时,我对它如何处理完全由空格组成的字符串感到失望。我希望它们被修剪成空字符串。相反,它们被原封不动地返回。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。你知道,因为我可以。

// "New and improved" version of trim. Lol.
std::string trim(std::string const& s)
{
    auto const first{ s.find_first_not_of(' ') };
    if (first == std::string::npos)
        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"

相关问题