ここでの違いは、基本的に 2 つの空の配列を使用して、それらを 1 つのメモリ空間にマージしようとしていることです (それがあなたにとって意味があるかどうかはわかりません)。
まず、C では、文字列を で終了する必要があります\0
。これは、Java では公開または表示されないものです。また、基本的に 2 つの未定義の文字列を使用しました (値が設定されていないため)。
#include <stdio.h>
#include <string.h>
char target[256];
const char source_a[] = "Hello";
const char source_b[] = "World!";
int void(main)
{
target[0] = '\0'; // this essentially empties the string as we set the first entry to be the end. Depending on your language version of C, you might as well write "char target[256] = {'\0'};" above.
strcat(target, source_a); // append the first string/char array
strcat(target, " "); // append a const string literal
strcat(target, source_b); // append the second string
printf("%s\n", target);
return 0;
}
重要:strcat()
長さチェックが実行されず、Java 以外では、これらの「文字列」は固定長 (変数を定義するときに設定した長さ) であるため、使用すると保存されない可能性があります。長さが指定されていない場合、初期化時に文字列をコピーすると、その長さが取得されます (たとえばchar test[] = "Hello!";
、7 文字の長さになります (終了するため\0
))。
文字列に対して Java のようなアプローチが必要な場合は、C++ とstd::string
クラスを使用してください。これは、Java の文字列にはるかに似た機能を実行します。