char
charとは
char is a variable type to have a character of one byte.
String is defined as an array or pointer of char.
charは,1バイトの文字を格納する変数型.
文字列はchar型変数の配列又はポインターとして定義される.
Sample 1: Define character and string as an array
Output.
Char is also interpreted as 1 byte integer, and its value is the one correspondant to ASCII character.
No value is given to str1, so no valid character is displayed.
The string str3 and str4 defined as pointers cannot be obtained with sizeof function because it returns the pointer size when a pointer was passed.
Charは1バイト整数として見なすこともでき,その値はASCII文字に対応する整数となる.
str1には値が代入されていないので有効な文字は出力されない.
sizeof関数はポインターを渡されるとポインターサイズを返すため,ポインターとして定義された文字列str3, str4の長さはsizeofで取得することが出来ない.
Length of string
Length of string can be obtained with
strlen function.
Include
string.h to use this function.
Also, string length can be obtained by searching for null character '\0' without using
string.h (
StrLength function in the following sample code).
文字列の長さは
strlen関数で取得することが出来る.
この関数を使うには
string.hを
includeする必要がある.
また,
string.hを使わず,
null文字 '\0' を検索して文字列を調べることもできる(下記サンプルコードの
StrLength関数).
Cited
C言語講座:文字列の長さを求める.
Output.
Copying string
In C, array cannot be substituted. So you have to copy characters one by one or use a function to copy a string.
Cでは配列の代入は出来ないので,文字列をコピーするには文字を一つずつコピーするか関数を使う必要がある.
strcpy(char *dst, const char *src)
char *dst: Destination string. コピー先の文字列.
const char *src: Source string. コピー元の文字列.
strncpy(char *dst, const char *src, int length)
char *dst: Destination string. コピー先の文字列.
const char *src: Source string. コピー元の文字列.
int length: Length to copy. コピーする長さ.
Output.
When copied characters one by one, it seems characters are randomly put in the empty slots in the destination string. This is same for function strncpy; it does not put null character '\0' after the copied string. You must put null character by yourself dependant on the purpose.
文字を一つずつコピーする場合,コピー先の文字列の空スロットにはランダムに値が入るようである.strncpyも同様で,この関数はコピーした文字列の後ろにnull文字を付けない.なので目的に応じて自分で付ける必要がある.
Be careful of the length of destination string.
コピー先文字列の長さに注意
In the following example, str3 has no space to have null character, so null character of str1 is not copied to str3.
And as the output shows, the value of str1 is lost after copying from str1 to str3. It doesn't happen when the copy from str1 to str2. I don't know the reason, but anyway you should make enough size of string for the destination string.
下の例ではstr3がnull文字をコピーする領域を持っていないので,str1のnull文字がコピーされない.
そして出力が示すように,str1からstr3へのコピーが行われた後str1の値が消えている.str1からstr2へのコピーを行わない場合この現象は生じない.理由は分からないが,いずれにしてもコピー先文字列には十分な大きさの文字列を用意しておくべきである.
Output.