c言語では、配列のサイズを超えて文字列が入力されるような状況でも、基本的にコンパイルエラーは起きないので注意する。
文字列操作
文字列の操作に関する型や関数のヘッダーファイル。
#include <stdio.h>
#include <string.h>
int main(void) {
char str_1[256];
char str_2[256];
char str_3[512];
unsigned long len;
printf("str_1:");
scanf("%s", str_1);
printf("str_2:");
scanf("%s", str_2);
// コピー
printf("copy str_1 to str_3...\n");
strcpy(str_3, str_1);
printf("str_3: %s\n", str_3);
// 結合
printf("concatinate str_3 and str_2...\n");
strcat(str_3, str_2);
printf("str_3: %s\n", str_3);
// 文字数
len = strlen(str_3);
printf("length of str_3: %lu\n", len);
// 文字列の比較
if (strcmp(str_1, str_2) == 0) {
printf("str_1 is equal to str_2.\n");
} else {
printf("str_1 is not equal to str_2.\n");
}
return 0;
}
c言語では、文字列を比較するとポインタの比較になるので、例えば == で同じ文字列かどうかの比較はできない。strcmp 関数を使う。
文字列と数値
atoi atof の a はascii。
sprintf(s, format, a) は、a をformatの書式文字列に従って、s が指す文字配列へ書き込む。
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char s1[256] = "12345";
char s2[256] = "1.23456789";
int num1;
double num2;
// 文字列を数値に変換
num1 = atoi(s1);
num2 = atof(s2);
printf("s1:%s num1:%d\n", s1, num1);
printf("s2:%s num2:%lf\n", s2, num2);
puts("bring num1 to s2 and num2 to s1...");
// 数値を文字列に変換
sprintf(s2, "%d", num1);
sprintf(s1, "%lf", num2);
printf("s1:%s num1:%d\n", s1, num1);
printf("s2:%s num2:%lf\n", s2, num2);
return 0;
}