【问题标题】:How to concatenate parts of a string?如何连接字符串的各个部分?
【发布时间】:2021-11-03 07:29:35
【问题描述】:
#include<bits/stdc++.h>
using namespace std;

int main()
{
    string str = "Hello"; 
    string s = str[0] + str[1];  
    cout << s;
    return 0;
}

即使我们可以连接字符串,为什么这段代码会出错?

【问题讨论】:

标签: c++ string data-structures concatenation string-concatenation


【解决方案1】:

失败的原因

std::string s = str[0] + str[1];

是因为str[0]str[1] 返回一个charHe):

std::string s = 'H' + 'e';

添加两个chars 不会连接它们,而是将它们的值相加。每个字符都有一个分配的数字(查找 ASCII 表)

std::string s = 72 + 101;

这将失败,因为将数字 173 分配给 string 对编译器来说并没有真正意义。


有多种方法可以将变量连接在一起,在这种情况下,最简单的解决方案是

std::string s { str[0], str[1] };

不过,这仅限于chars,所以你不能说{ str[0], str[1], 500 }。因此,连接任意数量数据的一般方法是使用std::ostringstream,在标题&lt;sstream&gt; 中找到。这是如何使用的:

std::ostringstream stream;
stream << str[0] << str[1] << 500;

std::string s = stream.str();

阅读here为什么using namespace std;被认为是不好的做法,here为什么要避免&lt;bits/stdc++.h&gt;

【讨论】:

    【解决方案2】:

    str[0]str[1] 给你的是字符,而不是字符串。添加它们会为您提供另一个字符,该字符不能转换为字符串。

    您可以使用要连接的字符串的第一部分的子字符串构造一个新字符串,然后插入要连接的字符串的第二部分的子字符串,如下所示:

    // Construct new string that contains the first character of str
    string s(str.begin(), str.begin() + 1);
    
    // Add the second character of str onto the end of s
    s.insert(s.end(), str.begin() + 1, str.begin() + 2);
    

    【讨论】:

    • 或者你可以做std::string s = std::string({str[0], str[1]});
    • 是的,如果你一次只做一个角色。更好的是string s{ str[0], str[1] }; 摆脱临时。迭代器只是为了可扩展性。当然,您必须更改 + 1s 和 + 2s,但仍然如此。
    猜你喜欢
    • 1970-01-01
    • 2011-06-27
    • 1970-01-01
    • 1970-01-01
    • 2022-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多