C の文字列は char という文字を一個だけ格納する型の配列になっています。
#include <stdio.h>
int main()
{
char hello[ ] = {'H', 'e', 'l', 'l', 'o'};
char world[6] = {'w', 'o', 'r', 'l', 'd'};
char again[6] = {'a', 'g', 'a', 'i', 'n', 0};
char excla[2] = {'!'}; // [2]以上なら[10]などでも良い
printf
("-------------------------------------------------------\n");
printf("%s " , hello);
printf("%s " , world);
printf("%s" , again);
printf("%s\n", excla);
char hello5[5] = {'H', 'e', 'l', 'l', 'o'};
char world5[5] = {'w', 'o', 'r', 'l', 'd'};
char again5[5] = {'a', 'g', 'a', 'i', 'n'};
char excla1[1] = {'!'};
printf("%s " , hello5);
printf("%sn" , world5);
printf("%s" , again5);
printf("%s\n", excla1);
char str[] = "Hello world again!";
printf("%s\n", str);
printf
("-------------------------------------------------------\n");
return 0;
}
-------------------------------------------------------
Hello world again!
Hello! worldHello!nagainworldHello!!againworldHello!
Hello world again!
-------------------------------------------------------
#include <stdio.h>
int main()
{
char *hello = "Hello world again!";
printf("%s\n", hello);
char *again[] = {"Hello ", "world ", "again!"};
printf("%s\n", *again);
for (int i = 0; i < 3; i++)
{
printf("%s", again[i]);
}
printf("\n");
char world[][50] = {"Hello ", "world ", "again!"};
printf("%s\n", *world);
for (int i = 0; i < 3; i++)
{
printf("%s", world[i]);
}
printf("\n");
return 0;
}
Hello world again!
Hello
Hello world again!
Hello
Hello world again!
#include <stdio.h>
int main()
{
char *strary[] = {"Hello", "world", "again!"};
int count = sizeof strary / sizeof strary[0];
printf("%d\n", count);
for (int i = 0; i < count; i++)
{
printf("%s\n", strary[i]);
}
return 0;
}
3
Hello
world
again!
#include <stdio.h>
#include <stdlib.h> // for atoi
int main()
{
char *str = "123";
printf("%d\n", *str); // 49 と表示される
printf("%d\n", '1'); // 49 と表示される
int num = atoi(str); // 文字"123"を整数123に変換
printf("%d\n", num); // 123 と表示される
printf("Enter number: ");
scanf("%d", &num);
printf(" You entered: %d\n", num);
return 0;
}
49
49
123
Enter number: 2005
You entered: 2005
#include <stdio.h>
//#include <stdlib.h> // 必要な場合があるかもしれません
int main()
{
int num = 2005;
char *str;
int c = snprintf(str, -1, "%d", num);
puts(str);
printf("%d\n", c);
float f = 10.5;
c = snprintf(str, -1, "%f", f);
puts(str);
printf("%d\n", c);
return 0;
}
2005
4
10.500000
9
#include <stdio.h>
#include <string.h> // for strcmp
int main ()
{
char *str1 = "あいうえお";
char *str2 = "かきくけこ";
printf("%d\n", strcmp(str1, str2));
str1 = "xyz";
str2 = "abc";
printf("%d\n", strcmp(str1, str2));
str1 = "C言語";
str2 = "C言語";
printf("%d\n", strcmp(str1, str2));
return 0;
}
-9
23
0