0% found this document useful (0 votes)
7 views38 pages

Strings

Uploaded by

ronddai818
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views38 pages

Strings

Uploaded by

ronddai818
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

計算機程式設計

Computer Programming

Strings

Instructor: 林英嘉
2024/11/25
W12 Slido: #3517219 GitHub repo
Outline

• Introduction to characters and strings


• Input characters and strings
• Array of strings
• Practical Questions

2
[Definition] Characters and Strings

• 字元:character
• 字串:string

'a' // this is a character `a`


"a" // this is a string `a`
"Sweet home" // this is a string `Sweet home`

Be careful!
• We should use single quotes (' ) for a character.
• We should use double quotes (") for a string.

3
[Declaration & Definition] Characters

Example:

char a_char = 'Y';

• char: abbreviation from the rst four letters of “character”


• a char variable takes 1 byte for storage (8 bits).
• The value range of a char variable is -128 to 127.

4
fi
資料類型比較

⼤⼩
Speci er 數值範圍
(Byte)*
int 4 %d -2,147,483,648 到 2,147,483,647 (範圍2的32次⽅)

char 1 %c -128 到 127 或 0 到 255 (取決於是否有符號)

float 4 %f 約 1.2E-38 到 3.4E+38,精度約 6 位⼗進制之⼩數

double 8 %lf 約 2.2E-308 到 1.7E+308,精度約 15-16 位⼗進制之⼩數

*In a 64-bit system

5
fi
[Declaration] String
C-course-materials/07-Strings/declaration.c

Strings are arrays of characters in which a special character—the null character—marks the end.

Example:

char str_11[11] = "Sweet home";

Array size can be omitted (compiler will allocate memory according to your string)

index 0 1 2 3 4 5 6 7 8 9 10
string S w e e t h o m e \0

Null character 6
[Usage] Specifier and Size Comparison

Type int char char float double

Double-precision
integer character string oating-point number
Meaning oating-point number
整數 字元 字串 浮點數
倍準浮點數

⼤⼩ (Byte)* 4 1 length+1 4 8

Speci er %d %c %s %f %lf

*In a 64-bit system

7
fl
fl
fi
Print chars and strings
C-course-materials/07-Strings/print_char_str.c

#include <stdio.h>
int main(void){
char a_char = 'Y';
printf("%c\n", a_char);

char a_string[] = "Y";


printf("%s\n", a_string);

char str_11[] = "Sweet home";


printf("%s\n", str_11);
}

Be careful!
• Use %c for printing a character
• Use %s for printing a string
8
Size comparison between chars and strings
C-course-materials/07-Strings/sizes.c

#include <stdio.h>
int main(void){
char a_char = 'Y';
printf("%d\n", sizeof(a_char));

char a_string[] = "Y";


printf("%d\n", sizeof(a_string));

char str_11[] = "Sweet home";


printf("%d\n", sizeof(str_11));
}

1
2 ‘\0’ is taken into consideration.
11

9
Check \0 in a string
C-course-materials/07-Strings/check_end.c

#include <stdio.h>
int main(void){
char str_11[] = "Sweet home";
for (int i = 0; i < sizeof(str_11); i++){
if (str_11[i] == '\0') {
printf("\\0");
} else {
printf("%c", str_11[i]);
}
}
}

‘\0’ cannot be printed! But we can still detect it.

10
Use \0 as the end of a loop
C-course-materials/07-Strings/end_in_for.c

#include <stdio.h>
int main(void){
char str_11[] = "Sweet home";
for (int i = 0; str_11[i] != '\0'; i++){
printf("%c", str_11[i]);
}
}

‘\0’ can be used as the stop criterion for a loop.

11
[Important Notes] About the null character \0

• ‘\0’ is a character that cannot be printed.


• ‘\0’ will be automatically added at the end if the length permitted.

This will automatically add \0:


char str_11[] = "Sweet home";
char str_11[11] = "Sweet home";

This will not automatically add \0:


char str_11[10] = "Sweet home";

12
[Declaration] Characters and Strings with an Initializer
C-course-materials/07-Strings/declaration_initializer.c

• You can also use an initializer to declare a char variable.

String example:

char str_5[5] = {'H', 'e', 'l', 'l', 'o'};

Array size can be omitted (compiler will allocate memory according to your string)

Character example:

char a_char = {'Y'};

13
[Important Notes] About the null character \0
• ‘\0’ is a character that cannot be printed.
• ‘\0’ will be automatically added at the end if the length permitted.
This will automatically add \0:
char str_5[6] = {'H', 'e', 'l', 'l', 'o'};
char str_5[] = {'H', 'e', 'l', 'l', 'o'};

This will not automatically add \0:


char str_5[5] = {'H', 'e', 'l', 'l', 'o'};

We can also manually add \0:

char str_5[6] = {'H', 'e', 'l', 'l', 'o', '\0'};


14
[Usage] You can’t do these
C-course-materials/07-Strings/declaration.c

char a_name = "Y";

Reason: a string must be stored in an array.

char a_name[] = 'S';


char a_char[] = {'Y'};

Reason: if a char variable is declared with an array, it should not be a character. It is a string.

15
When length exceeds the initializer
C-course-materials/07-Strings/shorter_initializer.c

#include <stdio.h>
int main(void){
char a_string[10] = "Hello";

16
When length exceeds the initializer
C-course-materials/07-Strings/shorter_initializer.c

Once the assigned length exceeds the number of elements in an initializer, ‘\0’ will be
appended to ll the remaining space until the array reaches the length.
#include <stdio.h>
int main(void){
char a_string[10] = "Hello";
for (int i = 0; i < sizeof(a_string); i++){
if (a_string[i] == '\0') {
printf("\\0");
} else {
printf("%c", a_string[i]);
}
}
}

index 0 1 2 3 4 5 6 7 8 9
string H e l l o \0 \0 \0 \0 \0
17
fi
[Introduction] ASCII

• ASCII (American Standard Code for Information Interchange)


• ASCII is a character encoding system to represent characters in computers.
• ASCII has just 128 (7 bit; from 0 to 127) code points, of which only 95 are
printable characters.

18
[Introduction] ASCII

Figure source: https://www.geeksforgeeks.org/ascii-table/ 19


Decimal to char via ASCII encodings
C-course-materials/07-Strings/decimal_to_char_ascii.c

• ASCII (American Standard Code for Information Interchange)


• Characters are internally represented by their ASCII codes, which can be displayed in decimals.

#include <stdio.h>
int main(void){
int nums[5] = {72, 101, 108, 108, 111};
char c;
for (int i = 0; i < 5; i++){
c = nums[i];
printf("%c", c);
}
}

20
Hexadecimal to char via ASCII encodings
C-course-materials/07-Strings/hex_to_char_ascii.c

• ASCII (American Standard Code for Information Interchange)


• Characters are internally represented by their ASCII codes, which can be displayed in hexadecimals.
• 0x is the pre x for hexadecimals in C. Hexadecimals are also integers.
#include <stdio.h>
int main(void){
/*
Hexadecimal values for 'H', 'e', 'l', 'l', 'o'
*/
int nums[5] = {0x48, 0x65, 0x6C, 0x6C, 0x6F};
char c;
for (int i = 0; i < 5; i++){
c = nums[i];
printf("%c", c);
}
}
21
fi
Print number from char via ASCII encodings
C-course-materials/07-Strings/print_num_from_char.c

• We can also print numerical values from characters.


#include <stdio.h>
int main(void){
char a_string[5] = "Hello";
for (int i = 0; i < sizeof(a_string); i++){
printf("Decimal: %d, ", a_string[i]);
printf("Hexadecimal: %x", a_string[i]);
printf("\n");
}
}

Decimal: 72, Hexadecimal: 48


Decimal: 101, Hexadecimal: 65
Decimal: 108, Hexadecimal: 6c
Decimal: 108, Hexadecimal: 6c
Decimal: 111, Hexadecimal: 6f
22
Passing a char variable to a function
C-course-materials/07-Strings/print_func.c

#include <stdio.h>
void print_char(char c){
printf("%c", c);
}

void print_str(char str[]){


for (int i = 0; str[i] != '\0'; i++){
print_char(str[i]);
}
}

int main(void){
char a_char = 'Y', str_5[] = "Hello";
print_char(a_char);
printf("\n");
print_str(str_5);
}
23
Input characters and strings
Input a character
C-course-materials/07-Strings/scanf_char.c

#include <stdio.h>
int main(void){
char c;
scanf("%c", &c);
printf("%c\n", c);
printf("Decimal: %d\n", c);
printf("Hexadecimal: %x\n", c);
}

• We can use scanf to read a single character.


• The character can be printed as a decimal or hexadecimal number.
25
Input a string
C-course-materials/07-Strings/scanf_str.c

#include <stdio.h>
int main(void){
char a_string[10];
scanf("%s", a_string);
printf("%s!", a_string);
return 0;
}

• A string, being an array of characters, represents the memory address of its rst
element.
• Therefore, we don’t need to use ‘&’ when using scanf to input a string.
26

fi
Memory address of a string
C-course-materials/07-Strings/str_addr.c

#include <stdio.h>
int main(void){
char a_string[] = "Hello";
printf("size: %d\n", sizeof(a_string));
printf("a_string: %p\n", a_string);
for (int i = 0; i < sizeof(a_string); i++){
printf("a_string[%d]: %p\n", i, &a_string[i]);
}
}

size: 6
a_string: 0x7fffffffdda2
a_string[0]: 0x7fffffffdda2
a_string[1]: 0x7fffffffdda3
a_string[2]: 0x7fffffffdda4
a_string[3]: 0x7fffffffdda5
a_string[4]: 0x7fffffffdda6
a_string[5]: 0x7fffffffdda7 Address of \0 27
Input multiple strings
C-course-materials/07-Strings/scanf_multi_str.c

#include <stdio.h>
int main(void){
char a_string[10];
while (scanf("%s", a_string) != EOF){
printf("Now the string is: %s\n", a_string);
for (int i = 0; i < sizeof(a_string); i++){
if (a_string[i] == '\0') {
break;
}
printf("%c ", a_string[i]);
}
}
return 0;
}

• scanf will return EOF if it encounters the end of the input stream.
28
Array of strings
[Declaration] Array of strings

Declaration

char strings_arr[num_of_strings][string_length];

Declaration with an initializer


char strings_arr[num_of_strings][string_length] = {“str1”,
“str2”, ...};

30
Array of strings (Declaration with an initializer)
C-course-materials/07-Strings/arr_strings.c

• We can directly assign strings to an array with an initializer.

#include <stdio.h>
int main(void){
char strings[3][10] = {"Tom", "Lily", "James Lee"};
for (int i = 0; i < 3; i++){
printf("strings[%d]: %s\n", i, strings[i]);
}
for (int i = 0; i < 3; i++){
printf("Addr strings[%d]:%p\n", i, strings[i]);
printf("Addr strings[%d][0]:%p\n", i, &strings[i][0]);
}
}

31
[Illustration] Array of strings
C-course-materials/07-Strings/arr_strings.c

strings[0] T o m \0 \0 \0 \0 \0 \0 \0

strings[1] L i l y \0 \0 \0 \0 \0 \0

strings[2] J a m e s L e e \0

32
Array of strings (value assignment with while)
C-course-materials/07-Strings/arr_strings_while.c

#include <stdio.h>
int main(void){
char strings[3][10];
int count = 0;
while (scanf("%s", strings[count]) != EOF){
printf("%s is read to the array.\n", strings[count]);
count++;
}
// strings[0] = "Tom";
// strings[1] = "Lily";
// strings[2] = "James Lee";
for (int i = 0; i < count; i++){
printf("strings[%d]: %s\n", i, strings[i]);
}
}

33
Practical Questions
[Question] Check if a String is a Palindrome
Write a C program to determine whether a given string is a palindrome.

• Input:
racecar

• Output:
Palindrome

• Input:
hello

• Output:
Not Palindrome
35
Check if a String is a Palindrome
C-course-materials/07-Strings/check_palindrome.c

#include <stdio.h>
#include <string.h>
int is_palindrome(char str[]) {
int length = strlen(str); // strlen excludes '\0'
for (int i = 0; i < length / 2; i++) {
if (str[i] != str[length - i - 1]) {
return 0;
}
}
return 1;
}

index 0 1 2 3 4
string H e l l o
36
Check if a String is a Palindrome
C-course-materials/07-Strings/check_palindrome.c

int main(void) {
char str[100];
printf("Please enter a string: ");
scanf("%s", str);
if (is_palindrome(str)) {
printf("Palindrome\n");
} else {
printf("Not a palindrome\n");
}
return 0;
}

37
[Questions] W12 Quiz

• Q1:
• Name the code into `studentID_q1.c `
• Q2:
• Name the code into `studentID_q2.c `
• Compress your code into `studentID_w12quiz.zip` and upload it.

38

You might also like