将两个const char *组合在一起

时间:2013-09-02 20:21:25

标签: c++ string char const

我已经尝试了很多方法来做到这一点,我得到了一个静态的空白,并且在我制作的Console类中,Void它自我工作正常:

Console::WriteLine(const char* msg)

另一方面,我得到了另一个const char * non static void,它调用了来自它的Console :: WriteLine,我已经在C#上工作了大约一年,在C#上我可以很容易地做到这样的事情:

string a = "Start ";
string b = a + "End";

当我在C ++上调用它时,它给了我一堆错误:

Player::Kill(const char* Message)
{
    Console::WriteLine("> " + Message + " <");
}

我也尝试了strcat的东西并且放了,但是它告诉我使用strcat_s并没有真正起作用,而且我也试过做字符串而不是const char *,并尝试了char *,但是所有他们为我正在尝试的事情提供错误。

6 个答案:

答案 0 :(得分:7)

“const”表示“不能更改(* 1)”。因此,您不能简单地将一个const char字符串“添加”到另一个(* 2)。你可以做的是将它们复制到非const字符缓冲区。

const char* a = ...;
const char* b = ...;

char buffer[256]; // <- danger, only storage for 256 characters.
strncpy(buffer, a, sizeof(buffer));
strncat(buffer, b, sizeof(buffer));

// now buffer has the two strings joined together.

您出于类似原因尝试使用std :: string失败。你说:

std::string a = "Start";
std::string b = a + " End";

这转换为

b = (std::string)a + (const char*)" End";

除了它创建一个额外的字符串,你可能想要的是

之外,哪个应该没问题
std::string a = "Start";
a += " End";

如果您收到编译错误,请发布它们(确保#include)。

或者你可以这样做:

std::string addTwoStrings(const std::string& a, const std::string& b)
{
    return a + b; // works because they are both strings.
}

以下所有工作:(请参阅实时演示http://ideone.com/Ytohgs

#include <iostream>
#include <string>

std::string addTwoStrings(const std::string& a, const std::string& b)
{
    return a + b; // works because they are both strings.
}

void foo(const char* a, const char* b)
{
    std::string str = a;
    std::cout << "1st str = [" << str << "]" << std::endl;
    str += " ";
    std::cout << "2nd str = [" << str << "]" << std::endl;
    str += b;
    std::cout << "3rd str = [" << str << "]" << std::endl;
    str = addTwoStrings(a, " ");
    std::cout << "4th str = [" << str << "]" << std::endl;
    str = addTwoStrings(str, b);
    std::cout << "5th str = [" << str << "]" << std::endl;
}

int main()
{
    foo("hello", "world");
}

* 1或者更确切地说,“无法原位更改” - 您可以在表达式等中使用它,例如,例如。

const size_t len = strlen("hello");
size_t newLen = len + strlen("world");
// but this would not be legal:
len += 2; // error: len is const.

2“const char a + const char * b”实际上是试图添加两个指针而不是两个字符串,结果将是字符串的地址加上字符串b的地址,其总和将是一些随机存储位置

答案 1 :(得分:3)

char *是一个指针("> "" <"也是如此),您无法将指针添加到一起。

但是,您可以使用+运算符连接C ++字符串:

Player::Kill(const std::string& Message)
{
    Console::WriteLine(("> " + Message + " <").c_str());
}

答案 2 :(得分:2)

为什么不单独输出3个字符串,而不是连接字符串并创建额外的临时对象?

Player::Kill(const char* Message)
{
  Console::Write("> ");
  Console::Write(Message);
  Console::WriteLine(" <");
}

答案 3 :(得分:1)

既然你说它是C ++代码,就这样:

void Player::Kill(std::string const& Message)
{
    Console::WriteLine(("> " + Message + " <").c_str());
}

理想情况下,您宣布Console::WriteLine()也需要std::string const&,在这种情况下,您无需执行.c_str() - 舞蹈。

答案 4 :(得分:-1)

#include <iostream>
using namespace std;

string string1 = "John";
string string2 = "Smith";

float string1Len = string1.length();
float combinedLen = string1.length() + string2.length();
char combine[string2.length() + string1.length()];

for(int i = 0; i < string1Len; ++i){
    combine[i] = string1[i];
}
for(int i = string1Len; i < combinedLen; ++i){
    combine[i] = string2[i - string1Len];
}

const char * combined = combine;

答案 5 :(得分:-1)

好吧,可以使用 const char* 进行更改,即使认为它是 const 我们也不能更改其值但可以更改其地址,请查看下面的类以供参考

    class String
{
private:
    const char* m_Name;
    int m_Size;
public:
    String() :m_Name(" "), m_Size(0) { m_Size = 0; }
    String(const char* name , int size) :m_Name(name),m_Size(size) {}
    String(const char* name) :m_Name(name) {}

    void Display()
    {
        LOG(m_Name);
    }
    int GetSize()
    {
        while (m_Name[m_Size] != '\0')
        {
            m_Size++;
        }
        return m_Size;
    }
    void Append(const char* nameToAppend)
    {
        //Create an empty char array pointer "*tempPtr" of size = existing const 
        //char name pointer "m_Name"  + const char pointer appending name 
        //"*nameExtention" 
        
        //this array can store both the names 
        int totalSize = 0;
        int nameToAppendSize = 0, existingNameSize = 0;
        while (nameToAppend[nameToAppendSize] != '\0')
        {nameToAppendSize++;}
        existingNameSize = this->GetSize();
        totalSize = nameToAppendSize + existingNameSize;
        char* tempPtr = new char[totalSize+1];

        //Add  existing const char name pointer "*m_Name"  +  const char pointer 
        //appending name "*nameExtention" to tempPtr,  using a loop 
        
        int currentSize = 0;
        for (int i = 0; i < existingNameSize; i++)
        {   
            tempPtr[currentSize] = m_Name[i];
            currentSize++;
        }
        for (int i = 0; i <= nameToAppendSize; i++)
        {
            if (i == nameToAppendSize)
            {
                tempPtr[currentSize] = '\0'; // this line tells compiler to stop 
                                             //  writting inside tempPtr 
            }
            else
            {
                tempPtr[currentSize] = nameToAppend[i];
                currentSize++;
            }
        }
        //--------------------------------
        //Now change the address of your const char* with tempPtr
        //This will change the contents of the const char* 
        //--------------------------------
        m_Name = (char*)tempPtr;
    }
};