回答:
まず、char*orを使用しないでください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+=割り当て解除と割り当ての両方を実行します。ヒープ割り当ては、私たちが通常行う最も高価な操作の1つです。
Cでプログラミングしている場合、name実際に固定長配列であると想定すると、次のようにする必要があります。
char filename[sizeof(name) + 4];
strcpy (filename, name) ;
strcat (filename, ".txt") ;
FILE* fp = fopen (filename,...
みなさんがなぜおすすめするのstd::stringでしょうか?
strcat()があります「Cスタイルの文字列」連結を行う、移植された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()通常はより良い代替手段である機能もあります
strncat2つ目のパラメーターの長さがわかっているため、ここでは関係ありません".txt"。ですから、それだけstrncat(name, ".txt", 4)では何も得られません。
strcat(destination、source)は、c ++で2つの文字列を連結するために使用できます。
深く理解するには、次のリンクを参照してください。
古いスタイルの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;
}