【问题标题】:append chars to string将字符附加到字符串
【发布时间】:2020-04-22 21:04:47
【问题描述】:

我有两个字符,我想创建一个连接它们的字符串:

char a = '1';
char b = '2';

string s = "(" + a + "," + b + ")";

实现这一目标的最简单方法是什么? 由于第一个元素“(”是一个字符串,通过从左到右连接元素应该可以工作,因为每个字符都将被转换为字符串并附加。

但是编译器似乎不喜欢它。

error: invalid operands of types 'const char*' and 'const char [2]' to binary 'operator+'

我怎样才能做到这一点?

【问题讨论】:

  • similar question。您会收到特定错误,因为在 "(" + a 中,a 被转换为 int,并且 add 给出了一个指针。然后你尝试将"," 添加到它。
  • 我喜欢这样的字符串流:std::ostringstream strm; strm << "(" << a << "," << b << ")";

标签: c++ string char


【解决方案1】:

"(" 不是std::string。它是一个char[2] C 字符串数组。使用s literal 使其成为std::string

using namespace std::string_literals;
std::string s = "("s + a + ","s + b + ")"s;

如果您尝试执行以下操作,这仍然会失败:

std::string s = a + b + "."s; // error

在这种情况下,您可以简单地从一个空字符串开始:

std::string s = ""s + a + b + "."s;

另一种选择是使用std::ostringstream 来构建字符串:

std::ostringstream oss;
oss << "(" << a << "," << b << ")";
std::string s3 = oss.str();

【讨论】:

  • 内置文字在技术上算作用户定义的文字吗?据我所知,UDL 后缀必须以 _ 开头。
  • 我不知道 s 字面量,谢谢!我喜欢这个解决方案,因为它紧凑、清晰并且不需要额外的复杂行。
【解决方案2】:

你可以写

char a = '1';
char b = '2';

std::string s = std::string( "(" ) + a + "," + b + ")";

或者

char a = '1';
char b = '2';

string s;

for ( char c : { '(', a, ',', b, ')' } )
{
    s += c;
}

这是一个演示程序。

#include <iostream>
#include <string>

int main() 
{
    char a = '1';
    char b = '2';

    std::string s = std::string( "(" ) + a + "," + b + ")";

    std::cout << "s = " << s << '\n';

    std::string t;

    for ( char c : { '(', a, ',', b, ')' } )
    {
        t += c;
    }

    std::cout << "t = " << t << '\n';

    return 0;
}

程序输出是

s = (1,2)
t = (1,2)

或者你可以只使用像这样的构造函数

std::string s( { '(', a, ',', b, ')' } );

或者方法assign

std::string s;
s.assign( { '(', a, ',', b, ')' } );

或附加

std::string s;
s.append( { '(', a, ',', b, ')' } );

这是另一个演示程序。

#include <iostream>
#include <string>

int main() 
{
    char a = '1';
    char b = '2';

    std::string s1( { '(', a, ',', b, ')' } );

    std::cout << "s1 = " << s1 << '\n';

    std::string s2;
    s2.assign( { '(', a, ',', b, ')' } );

    std::cout << "s2 = " << s2 << '\n';

    std::string s3( "The pair is " );
    s3.append( { '(', a, ',', b, ')' } );

    std::cout << "s3 = " << s3 << '\n';

    return 0;
}

它的输出是

s1 = (1,2)
s2 = (1,2)
s3 = The pair is (1,2)

【讨论】:

  • 您的for 循环可以替换为对std::string::append() 的一次调用:s.append({ '(', a, ',', b, ')' });
猜你喜欢
  • 1970-01-01
  • 2012-05-28
  • 2012-10-04
  • 1970-01-01
  • 2012-12-05
  • 2013-02-09
  • 2012-01-12
  • 1970-01-01
  • 2012-09-14
相关资源
最近更新 更多