// ***C Programming Cheatsheet***
// --- Strings Basics ---
#include <stdio.h>
#include <string.h>
/* --- 1. 基本字元與字串宣告 --- */
// 宣告字元
char a_char = 'Y' ; // 單引號用於字元
// 宣告字串
char a_string[ ] = "Hello" ; // 雙引號用於字串
char str_11[ 11 ] = "Sweet home" ; // 陣列大小指定為11
/* --- 2. 打印字元與字串 --- */
void print_example( ) {
char a_char = 'Y' ;
printf ( "%c\n " , a_char
) ; // 打印字元
char a_string[ ] = "Hello" ;
printf ( "%s\n " , a_string
) ; // 打印字串
char str_11[ ] = "Sweet home" ;
printf ( "%s\n " , str_11
) ; // 打印多字元字串 }
/* --- 3. 字串大小比較 --- */
void size_comparison( ) {
char a_char = 'Y' ;
char a_string[ ] = "Y" ;
char str_11[ ] = "Sweet home" ;
printf ( "Size of char: %lu\n " , sizeof ( a_char
) ) ; // 1 byte printf ( "Size of string 'Y': %lu\n " , sizeof ( a_string
) ) ; // 2 bytes (包含\0) printf ( "Size of string 'Sweet home': %lu\n " , sizeof ( str_11
) ) ; // 11 bytes }
/* --- 4. 使用\0檢測字串結尾 --- */
void check_null_char( ) {
char str_11[ ] = "Sweet home" ;
for ( int i = 0 ; i < sizeof ( str_11) ; i++ ) {
if ( str_11[ i] == '\0 ' ) {
} else {
}
}
}
/* --- 5. 字串反向檢查是否為回文 --- */
int is_palindrome( char str[ ] ) {
for ( int i = 0 ; i < length / 2 ; i++ ) {
if ( str[ i] != str[ length - i - 1 ] ) {
return 0 ;
}
}
return 1 ;
}
void palindrome_example( ) {
char str[ ] = "racecar" ;
if ( is_palindrome( str) ) {
printf ( "%s is a palindrome\n " , str
) ; } else {
printf ( "%s is not a palindrome\n " , str
) ; }
}
/* --- 6. ASCII 與字元對應 --- */
void ascii_example( ) {
char a = 'H' ;
printf ( "Character: %c, ASCII: %d\n " , a
, a
) ; // 打印字元及其 ASCII 值
int nums[ 5 ] = { 72 , 101 , 108 , 108 , 111 } ;
for ( int i = 0 ; i < 5 ; i++ ) {
printf ( "%c" , nums
[ i
] ) ; // ASCII 轉字元 }
}
/* --- 7. 讀取與輸入字串 --- */
void input_string_example( ) {
char input[ 20 ] ;
scanf ( "%19s" , input
) ; // 讀取最多 19 個字元 printf ( "You entered: %s\n " , input
) ; }
int main( ) {
print_example( ) ;
size_comparison( ) ;
check_null_char( ) ;
palindrome_example( ) ;
ascii_example( ) ;
input_string_example( ) ;
return 0 ;
}
Ly8gKioqQyBQcm9ncmFtbWluZyBDaGVhdHNoZWV0KioqCi8vIC0tLSBTdHJpbmdzIEJhc2ljcyAtLS0KCiNpbmNsdWRlIDxzdGRpby5oPgojaW5jbHVkZSA8c3RyaW5nLmg+CgovKiAtLS0gMS4g5Z+65pys5a2X5YWD6IiH5a2X5Liy5a6j5ZGKIC0tLSAqLwoKLy8g5a6j5ZGK5a2X5YWDCmNoYXIgYV9jaGFyID0gJ1knOyAvLyDllq7lvJXomZ/nlKjmlrzlrZflhYMKCi8vIOWuo+WRiuWtl+S4sgpjaGFyIGFfc3RyaW5nW10gPSAiSGVsbG8iOyAvLyDpm5nlvJXomZ/nlKjmlrzlrZfkuLIKY2hhciBzdHJfMTFbMTFdID0gIlN3ZWV0IGhvbWUiOyAvLyDpmaPliJflpKflsI/mjIflrprngroxMQoKLyogLS0tIDIuIOaJk+WNsOWtl+WFg+iIh+Wtl+S4siAtLS0gKi8Kdm9pZCBwcmludF9leGFtcGxlKCkgewogICAgY2hhciBhX2NoYXIgPSAnWSc7CiAgICBwcmludGYoIiVjXG4iLCBhX2NoYXIpOyAvLyDmiZPljbDlrZflhYMKCiAgICBjaGFyIGFfc3RyaW5nW10gPSAiSGVsbG8iOwogICAgcHJpbnRmKCIlc1xuIiwgYV9zdHJpbmcpOyAvLyDmiZPljbDlrZfkuLIKCiAgICBjaGFyIHN0cl8xMVtdID0gIlN3ZWV0IGhvbWUiOwogICAgcHJpbnRmKCIlc1xuIiwgc3RyXzExKTsgLy8g5omT5Y2w5aSa5a2X5YWD5a2X5LiyCn0KCi8qIC0tLSA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