将2个字符串连接在一起

时间:2013-04-10 12:01:29

标签: c++ string

我有两个字符串:

string word;
string alphabet;

word有一些我传递给的内容;让我们说"XYZ"

alphabet的字母除了XYZ,所以它是"ABCDEFGHIJKLMNOPQRSTUVW"

当我尝试用“+ =”连接它们时,我得到的只是word(即"XYZ")。我想让它看起来像这样:

XYZABCDEFGHIJKLMNOPQRSTUVW 

我做错了什么?代码基本上就是这个vvvv

=========================== encryption.cpp ================= ================================

#include <cstdlib>
#include <iostream>
#include "encryption.h"
#include <string>

encryption::encryption()
{
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

}


string encryption::removeletter(string word,char letter)
{
    //remove letter
    string temp;
    int indis=0;
    for(int i = 0; word[i] != '\0'; i++)
    {
        if(word[i] != letter)
            {
                temp[indis]=word[i] ;
                indis++;
            }

    }

    word=temp;

    return word;
}

This is the function i have proplems with :

    void encryption::encrypt(string word)//main.cpp is just calling this atm
    {
        string temp;
        int pos;
         //getting rid of the repeating letters
        for(int i = 0; i < word.length(); i++)
        {
            if( (pos = temp.find(kelime[i])) < 0)
                temp += word[i];
        }
        word=temp;//that ends here
        //taking words letters out of the alphabet
        for(int i = 0; i < word.length(); i++)
        {
            alfabet=removeletter(alfabe,word[i]);

        }
        for(int i = 0; i < word.length()-1; i++)
        {
            for(int j=0;alfabet[j] !='\0'; j++)
                if(alfabet[j+1] =='\0') alfabet[j]='\0';
        }

        /* I tried += here */
    }

=========================== encryption.h ================= ===================================

#ifndef encryption_h
#define encryption_h
#include<string>

    class encryption

    {
    public:
        encryption();

        void encrypt(string word);
        string removeletter(string word,char letter);
        //some other functions,i deleted them atm

    public:
            string alphabet;
            string encryptedalphabet;
            //staff that not in use atm(deleted)

    };

#endif

===========================的main.cpp ================= =====================================

#include <cstdlib>
#include <iostream>
#include "encryption.h"
#include <string>

string word;
encryption encrypted;
cin>>word;
encrypted.encrypt( word);

3 个答案:

答案 0 :(得分:1)

+=就是这样做的,你必须做其他事情。

string word = "XYZ";
string alphabet = "ABCDEFGHIJKLMNOPQRSTUVW";
alphabet += word;
cout << alphabet << "\n";

输出

ABCDEFGHIJKLMNOPQRSTUVWXYZ

答案 1 :(得分:0)

使用

append(字母);

请注意,当您想要连接多个字符串时,使用stringstream来避免不必要的字符串复制会更有效。

答案 2 :(得分:0)

string word = "XYZ";

string alphabet = "ABCDEFGHIJKLMNOPQRSTUVW";

word += alphabet;

现在你可以打印'word',你会找到答案。