Answers:
首先,请勿使用char*
或char[N]
。使用std::string
,那么其他一切都变得如此简单!
例子,
std::string s = "Hello";
std::string greet = s + " World"; //concatenation easy!
很简单,不是吗?
现在,如果char const *
由于某种原因(例如,当您想传递给某个函数)需要时,可以执行以下操作:
some_c_api(s.c_str(), s.size());
假设此函数声明为:
some_c_api(char const *input, size_t length);
std::string
从这里开始探索自己:
希望能有所帮助。
既然是C ++,为什么不使用std::string
代替char*
?串联将是微不足道的:
std::string str = "abc";
str += "another";
operator+=
执行解除分配和分配。堆分配是我们通常最昂贵的操作之一。
如果您使用C语言进行编程,则假设name
确实是一个像您所说的固定长度数组,则必须执行以下操作:
char filename[sizeof(name) + 4];
strcpy (filename, name) ;
strcat (filename, ".txt") ;
FILE* fp = fopen (filename,...
您现在知道为什么每个人都推荐std::string
吗?
移植的C库中有一个strcat()函数,它将为您执行“ C样式字符串”串联。
顺便说一句,即使C ++有很多函数可以处理C样式的字符串,但尝试并提出自己的函数来这样做可能会有所帮助,例如:
char * con(const char * first, const char * second) {
int l1 = 0, l2 = 0;
const char * f = first, * l = second;
// step 1 - find lengths (you can also use strlen)
while (*f++) ++l1;
while (*l++) ++l2;
char *result = new char[l1 + l2];
// then concatenate
for (int i = 0; i < l1; i++) result[i] = first[i];
for (int i = l1; i < l1 + l2; i++) result[i] = second[i - l1];
// finally, "cap" result with terminating null char
result[l1+l2] = '\0';
return result;
}
...然后...
char s1[] = "file_name";
char *c = con(s1, ".txt");
...的结果是file_name.txt
。
您可能还会想编写自己的代码,operator +
但是IIRC运算符仅允许使用指针重载,因为不允许使用参数。
另外,不要忘记在这种情况下结果是动态分配的,因此,您可能要在其上调用delete以避免内存泄漏,或者可以修改该函数以使用堆栈分配的字符数组,当然前提是它具有足够的长度。
strncat()
功能通常是更好的选择
strncat
在这里无关紧要,因为我们已经知道第二个参数的长度".txt"
。这样就不会strncat(name, ".txt", 4)
带来任何好处。
strcat(destination,source)可用于在c ++中连接两个字符串。
要深入了解,您可以在以下链接中查找-
最好使用C ++字符串类而不是旧样式的C字符串,生活会容易得多。
如果您已有旧样式的字符串,则可以隐藏到字符串类
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
cout<<greeting + "and there \n"; //will not compile because concat does \n not work on old C style string
string trueString = string (greeting);
cout << trueString + "and there \n"; // compiles fine
cout << trueString + 'c'; // this will be fine too. if one of the operand if C++ string, this will work too
//String appending
#include <iostream>
using namespace std;
void stringconcat(char *str1, char *str2){
while (*str1 != '\0'){
str1++;
}
while(*str2 != '\0'){
*str1 = *str2;
str1++;
str2++;
}
}
int main() {
char str1[100];
cin.getline(str1, 100);
char str2[100];
cin.getline(str2, 100);
stringconcat(str1, str2);
cout<<str1;
getchar();
return 0;
}