fork download
  1. // ***C Programming Cheatsheet***
  2. // --- Strings Basics ---
  3.  
  4. #include <stdio.h>
  5. #include <string.h>
  6.  
  7. /* --- 1. 基本字元與字串宣告 --- */
  8.  
  9. // 宣告字元
  10. char a_char = 'Y'; // 單引號用於字元
  11.  
  12. // 宣告字串
  13. char a_string[] = "Hello"; // 雙引號用於字串
  14. char str_11[11] = "Sweet home"; // 陣列大小指定為11
  15.  
  16. /* --- 2. 打印字元與字串 --- */
  17. void print_example() {
  18. char a_char = 'Y';
  19. printf("%c\n", a_char); // 打印字元
  20.  
  21. char a_string[] = "Hello";
  22. printf("%s\n", a_string); // 打印字串
  23.  
  24. char str_11[] = "Sweet home";
  25. printf("%s\n", str_11); // 打印多字元字串
  26. }
  27.  
  28. /* --- 3. 字串大小比較 --- */
  29. void size_comparison() {
  30. char a_char = 'Y';
  31. char a_string[] = "Y";
  32. char str_11[] = "Sweet home";
  33.  
  34. printf("Size of char: %lu\n", sizeof(a_char)); // 1 byte
  35. printf("Size of string 'Y': %lu\n", sizeof(a_string)); // 2 bytes (包含\0)
  36. printf("Size of string 'Sweet home': %lu\n", sizeof(str_11)); // 11 bytes
  37. }
  38.  
  39. /* --- 4. 使用\0檢測字串結尾 --- */
  40. void check_null_char() {
  41. char str_11[] = "Sweet home";
  42. for (int i = 0; i < sizeof(str_11); i++) {
  43. if (str_11[i] == '\0') {
  44. printf("\\0");
  45. } else {
  46. printf("%c", str_11[i]);
  47. }
  48. }
  49. printf("\n");
  50. }
  51.  
  52. /* --- 5. 字串反向檢查是否為回文 --- */
  53. int is_palindrome(char str[]) {
  54. int length = strlen(str);
  55. for (int i = 0; i < length / 2; i++) {
  56. if (str[i] != str[length - i - 1]) {
  57. return 0;
  58. }
  59. }
  60. return 1;
  61. }
  62.  
  63. void palindrome_example() {
  64. char str[] = "racecar";
  65. if (is_palindrome(str)) {
  66. printf("%s is a palindrome\n", str);
  67. } else {
  68. printf("%s is not a palindrome\n", str);
  69. }
  70. }
  71.  
  72. /* --- 6. ASCII 與字元對應 --- */
  73. void ascii_example() {
  74. char a = 'H';
  75. printf("Character: %c, ASCII: %d\n", a, a); // 打印字元及其 ASCII 值
  76.  
  77. int nums[5] = {72, 101, 108, 108, 111};
  78. for (int i = 0; i < 5; i++) {
  79. printf("%c", nums[i]); // ASCII 轉字元
  80. }
  81. printf("\n");
  82. }
  83.  
  84. /* --- 7. 讀取與輸入字串 --- */
  85. void input_string_example() {
  86. char input[20];
  87. printf("Enter a string: ");
  88. scanf("%19s", input); // 讀取最多 19 個字元
  89. printf("You entered: %s\n", input);
  90. }
  91.  
  92. int main() {
  93. print_example();
  94. size_comparison();
  95. check_null_char();
  96. palindrome_example();
  97. ascii_example();
  98. input_string_example();
  99. return 0;
  100. }
  101.  
Success #stdin #stdout 0s 5280KB
stdin
Standard input is empty
stdout
Y
Hello
Sweet home
Size of char: 1
Size of string 'Y': 2
Size of string 'Sweet home': 11
Sweet home\0
racecar is a palindrome
Character: H, ASCII: 72
Hello
Enter a string: You entered: o