【问题标题】:Inserting string in another string at specific index c++/Qt在特定索引c ++ / Qt的另一个字符串中插入字符串
【发布时间】:2016-04-10 00:13:10
【问题描述】:

我有一个 QString (这可能没关系,因为我将它转换为 std::string 无论如何),它包含文件的完整 unix 路径。例如/home/user/folder/name.of.another_file.txt.

我想在此文件名的扩展名之前附加另一个字符串。例如我传递给函数“positive”,这里我称之为vector_name,最后我想得到/home/user/folder/name.of.another_file_positive.txt(注意最后一个下划线应该由函数本身添加。

这是我的代码,但它不能编译,很遗憾!!

QString temp(mPath); //copy value of the member variable so it doesnt change???

std::string fullPath = temp.toStdString();
std::size_t lastIndex = std::string::find_last_of(fullPath, ".");
std::string::insert(lastIndex, fullPath.append("_" + vector_name.toStdString()));

std::cout << fullPath;

我收到以下错误:

error: cannot call member function 'std::basic_string<_CharT, _Traits, _Alloc>::size_type std::basic_string<_CharT, _Traits, _Alloc>::find_last_of(const std::basic_string<_CharT, _Traits, _Alloc>&, std::basic_string<_CharT, _Traits, _Alloc>::size_type) const [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>; std::basic_string<_CharT, _Traits, _Alloc>::size_type = long unsigned int]' without object
         std::size_t lastIndex = std::string::find_last_of(fullPath, ".");

cannot call member function 'std::basic_string<_CharT, _Traits, _Alloc>& std::basic_string<_CharT, _Traits, _Alloc>::insert(std::basic_string<_CharT, _Traits, _Alloc>::size_type, const std::basic_string<_CharT, _Traits, _Alloc>&) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>; std::basic_string<_CharT, _Traits, _Alloc>::size_type = long unsigned int]' without object
     std::string::insert(lastIndex, fullPath.append("_" + vector_name.toStdString()));

附:如果您也能告诉我如何使用 QString 或 Qt 库本身来实现这一点,我真的很感激!

【问题讨论】:

  • std::size_t lastIndex = full_path.find_last_of("."); 怎么样?它是成员函数而不是静态函数。 insert 也是如此。
  • QString 也有lastIndexOfappendinsert

标签: c++ qt stdstring qstring


【解决方案1】:

错误原因是find_last_ofinsertstd::string的成员函数,不是静态或非成员函数。因此,您需要一个对象来访问该函数。

更正如下:

std::size_t lastIndex = fullPath.find_last_of(".");
fullPath.insert(lastIndex, "_" + vector_name.toStdString());
cout << fullPath;

Live Example using dummy data

此外,您可能希望测试这些函数调用的返回值。如果文件名中没有"."怎么办?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-17
    • 1970-01-01
    • 2022-12-22
    • 2019-07-03
    • 2012-08-14
    相关资源
    最近更新 更多