从字符串修剪空格 [英] Trim whitespace from a String

查看:71
本文介绍了从字符串修剪空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在Java和C中有几种不错的方法,但是在C ++中,我似乎找不到轻松实现字符串修剪函数的方法。

I know there are several ways to do this in Java and C that are nice, but in C++ I can't seem to find a way to easily implement a string trimming function.

这是我目前拥有的:

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

但是每当我尝试拨打电话

but whenever I try and call

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行代码,我尝试使用regex,但无法使其正常工作。

I am trying to find a simple and standard way of trimming leading and trailing whitespace from a string without it taking up 100 lines of code, and I tried using regex, but could not get that to work as well.

我也不能使用Boost。

推荐答案

您的代码很好。您所看到的是一个链接器问题。

Your code is fine. What you are seeing is a linker issue.

如果您将代码放在这样的单个文件中:

If you put your code in a single file like this:

#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,您将看到它起作用。

then do g++ test.cc and run a.out, you will see it works.

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

You should check if the file that contains the trim function is included in the link stage of your compilation process.

这篇关于从字符串修剪空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆