c++ - 如何组合两个字符串?

标签 c++ string strlen

题目要求在不使用<string>的情况下组合两个字符串(较长的字符串在前面,较短的字符串在较长的字符串后面)头文件。输入的每个字符串不能超过20个字符。 我的逻辑是:

  1. first use strlen to get the length of the str1 and str2,
  2. use str3 to store the longer string, and str4 to store the shorter.
  3. add str3 and str4 to str5

这是我的代码:

#include<iostream>
using namespace std;

int main()
{
    // combine two strings , longer in the front, and shorter 
    // after it. do not use strcat
    char str1[20],str2[20],str3[20],str4[20],str5[40];
    // str1 and str2 stores original data, str3 stores longer 
    // and str4 stores shorter, str5 stores total
    int j=0;
    cin.getline(str1,20);
    cin.getline(str2,20);
    if(strlen(str1)<=strlen(str2))
    // give longer string value to str3,shorter to str2
    {
        for (int i=0;i<20;i++)
        {
            str3[i]=str2[i];
            str4[i]=str1[i];
        }
    }
    else
    {
        for (int i=0;i<20;i++)
        {
            str3[i]=str1[i];
            str4[i]=str2[i];
        }
    }
    for(j=0;str3[j]!='\0';j++)
    {
        str5[j]=str3[j];
    }
    for(int i=j;i<40;i++)
    for(int m=0;m<20;m++)
    {
        str5[i]=str4[m];
    }
    cout<<str5<<endl;
    return 0;
}

这是输出:

enter image description here

我的问题是什么?两个字符串之间的那些字符是什么?谢谢!!

最佳答案

特别是因为您明确提到是初学者,所以解决方案是使用 std::string :

#include <iostream>
#include <string>

int main() {
    std::string a;
    getline(std::cin, a);

    std::string b;
    getline(std::cin, b);

    // Ensure that the longer string goes to the front.
    if (a.size() < b.size());
        swap(a, b);

    std::string result = a + b;

    std::cout << result << '\n';

    // Or, simply:
    std::cout << a << b << '\n';
}

这里的信息是,尽管 C++ 有一些怪癖,但如果您依赖它的库而不是从头开始实现每个低级操作,它就是一种非常高级的语言。

关于c++ - 如何组合两个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21576007/

相关文章:

c++ - "Isolate"来自 64 位数字的特定行/列/对角线

c++ - 对象数组的选择排序

C++20 字符串文字模板参数工作示例

c# - 识别字符串并正确操作

python - 用相应的减法结果替换字符串中的数字

c - 如何在标准 C 中创建一个新的 char*

c - 从未使用过 strlen 时 strlen 的段错误?

c++ - 雕刻 1.4 CSG - C2375 : 'cbrt' : redefinition; different linkage

python - 如何在字符串中搜索子字符串值?

c++ - 将一个数组中的 char 值分配给另一个数组中的 char 值