C ++ concat三个char *字符串组合在一起 [英] C++ concat three char* strings togther

查看:60
本文介绍了C ++ concat三个char *字符串组合在一起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C ++的新手,正在寻找一种将三个char *字符串连接在一起的方法?谁能给我看一些示例代码?

亲切的问候,

解决方案

在C ++中,通常将 std :: string 用于字符串.这样,您可以使用 + 运算符进行连接.例如:

  std :: string s = s1 + s2 + s3; 

其中 s1 s2 s3 是您在 std :: string 变量中保存的三个字符串./p>

如果您具有 s1 s2 s3 作为 char * const char * ,然后您将其编写方式有所不同.

  std :: string s = s1;//调用const char *构造函数s + = s2;//调用operator + =()重载,接受const char *s + = s3;//然后再次 

如果您确实要使用以null终止的C字符串和C字符串函数,则可以使用 strcpy 复制并使用 strcat 进行连接.

  char [SOME_LARGE_ENOUGH_VALUE] str;strcpy(str,s1);strcat(str,s2);strcat(str,s3); 

其中 s1 s2 s3 是您的三个字符串,分别为 char * const char* .

当然,选择 SOME_LARGE_ENOUGH_VALUE 是有趣的部分.如果这是一项学习练习,那么您可能想学习如何动态分配字符串.

  char * str =新的char [strlen(s1)+ strlen(s2)+ strlen(s3)+1]; 

然后,您可以使用上面的 strcpy strcat 随机播放.但是现在您有责任破坏分配的原始内存.因此,请考虑如何以健壮的方式执行此操作,然后使用 std :: string


从注释中看,您似乎想连接三个字符串,然后将结果字符串传递给接受C字符串的低级哈希函数.因此,我建议您使用 std :: string 完成所有工作.仅在最后一刻,当您调用哈希函数时,请使用 c_str()函数获取所连接字符串的 const char * 表示形式.

I am new to c++ and am looking for a way to concatenate three char* strings together ? Can anyone show me some sample code ?

Kind Regards,

解决方案

In C++ you typically use std::string for strings. With that you can concatenate with the + operator. For instance:

std::string s = s1 + s2 + s3;

where s1, s2 and s3 are your three strings held in std::string variables.

If you have s1, s2 and s3 as char* or const char* then you write it a little differently.

std::string s = s1; // calls const char* constructor
s += s2; // calls operator+=() overload that accepts const char*
s += s3; // and again

If you really want to use null-terminated C strings, and C string functions, then you use strcpy to copy and strcat to concatenate.

char[SOME_LARGE_ENOUGH_VALUE] str;
strcpy(str, s1);
strcat(str, s2);
strcat(str, s3);

where s1, s2 and s3 are your three strings as char* or const char*.

Of course, choosing SOME_LARGE_ENOUGH_VALUE is the fun part. If this is a learning exercise, then you might like to learn how to allocate the string dynamically.

char *str = new char[strlen(s1) + strlen(s2) + strlen(s3) + 1];

Then you can use the strcpy, strcat shuffle above. But now you are responsible for destroying the raw memory that you allocated. So, think about how to do that in a robust way, and then use std::string!


From the comments, it seems you want to concatenate three strings, and then pass the resulting string to a low-level hash function that accepts a C string. So, I suggest that you do all your work with std::string. Only at the last minute, when you call the hash function, use the c_str() function to get a const char* representation of the concatenated string.

这篇关于C ++ concat三个char *字符串组合在一起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆