追加到字符串的 C++

c++ appending to string

本文关键字:C++ 字符串 追加      更新时间:2023-10-16

有没有一种简单的方法可以将整数附加到字符串中?

我有一个这样的 for 循环:

for (int i = 0; i < text.length(); i++) {
  for (int g = 0; g < word.length(); g++) {
    if (text[i] == word[g]) {
      kodas.append(g);
    }
  }
}

我需要获取相等的数组索引,索引当然是整数类型。但是当我这样做时,我收到一个错误:

invalid conversion from ‘int’ to ‘const char*’ [-fpermissive]|

有没有办法解决这个问题?

如果您正在使用 std::strings: #include <sstream>,请使用字符串流

#include <sstream>
using namespace std;
string oldString = "old";
int toAppend = 5;
stringstream ss(toAppend);
string newString = oldString + ss.str();

newString将被"old5"

是的

例如,您可以:

  • 使用将整数转换为字符串的 itoa 函数
  • 让你的kodas成为ostringstream,并像cout一样"写"进去:kodas << g

最简单的是这样的:

if (kodas.empty()) { kodas += ' '; }
kodas += std::to_string(g);

如果您没有 C++11,请改用boost::lexical_cast<std::string>(g)

失败了一切,你可以做这样可怕的事情:

kodas += static_cast<std::ostringstream&>(std::ostringstream() << g).str();

itoa(),它是 into to alpha 函数,应该可以帮助你。 如果你想

> 有

几种方法可以在C++中将数字格式化为字符串,包括 sprintf()boost:lexical_cast() 等。请参阅庄园农场的字符串格式化程序以获得良好的比较和其他建议。此外,C++11 还有std::to_string.您的编译器可能尚未拥有它,也可能尚未拥有它。