Chapter 8 Character Arrays and Strings

Slides:



Advertisements
Similar presentations
C Characters & Strings Character Review Character Handling Library Initialization String Conversion Functions String Handling Library Standard Input/Output.
Advertisements

1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
Lecture 9. Lecture 9: Outline Strings [Kochan, chap. 10] –Character Arrays/ Character Strings –Initializing Character Strings. The null string. –Escape.
Lecture 20 Arrays and Strings
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Chapter 9 Strings Instructor: Alkar / Demirer. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-2 Strings stringC implements the string data.
Chapter 9 Character Strings
Chapter 10.
Strings in C. Strings are Character Arrays Strings in C are simply arrays of characters. – Example:char s [10]; This is a ten (10) element array that.
Chapter 9 Character Strings 9.1 Character String Constants A character string constant is a sequence of characters enclosed in double quotation mark. Examples.
BBS514 Structured Programming (Yapısal Programlama)1 Character Processing, Strings and Pointers,
STRING Dong-Chul Kim BioMeCIS UTA 10/7/
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI C-Style Strings Strings and String Functions Dale Roberts, Lecturer.
Lecturer: Omid Jafarinezhad Sharif University of Technology Department of Computer Engineering 1 Fundamental of Programming (C) Lecture 6 Array and String.
Chapter 8 Strings. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-2 Strings stringC implements the string data structure using arrays of.
Representing Strings and String I/O. Introduction A string is a sequence of characters and is treated as a single data item. A string constant, also termed.
Strings Programming Applications. Strings in C C stores a string in a block of memory. The string is terminated by the \0 character:
13. Strings. String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal.
Strings, Pointers and Tools
Today’s Material Strings Definition Representation Initialization
1 Pointers: Parameter Passing and Return. 2 Passing Pointers to a Function Pointers are often passed to a function as arguments  Allows data items within.
1 Arrays and Pointers The name of an array is a pointer constant to the first element. Because the array’s name is a pointer constant, its value cannot.
Dr. Sajib Datta Feb 21,  In the last class we discussed: ◦ Bubble sort  How it works  performance.
Strings. String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal may.
CSE 251 Dr. Charles B. Owen Programming in C1 Strings and File I/O.
ECE 103 Engineering Programming Chapter 29 C Strings, Part 2 Herbert G. Mayer, PSU CS Status 7/30/2014 Initial content copied verbatim from ECE 103 material.
13. Strings. String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal.
Principles of Programming - NI Chapter 10: Character & String : In this chapter, you’ll learn about; Fundamentals of Strings and Characters The difference.
MULTI-DIMENSION ARRAY STRING Computer Programming Asst. Prof. Dr. Choopan Rattanapoka and Asst. Prof. Dr. Suphot Chunwiphat.
String in C++. 2 Using Strings in C++ Programs String library or provides functions to: - manipulate strings - compare strings - search strings ASCII.
1 Chapter 8 – Character Arrays and Strings Outline 8.1Introduction 8.2Declaring and Initializing String 8.3Input/output of strings 8.4String-handling Functions.
Introduction to Programming Using C Arrays. 2 Contents Arrays Subscripting.
מערכים (arrays) 02 אוקטובר אוקטובר אוקטובר 1602 אוקטובר אוקטובר אוקטובר 1602 אוקטובר אוקטובר אוקטובר 16 Department.
Chapter 9 - Formatted Input/Output
Introduction Programs which manipulate character data don’t usually just deal with single characters, but instead with collections of them (e.g. words,
Computer Organization and Design Pointers, Arrays and Strings in C
Chapter 8 “Character Arrays and Strings” Prepared by: Prof. Ajay M. Patel CE, IDS, NU.
Course Contents KIIT UNIVERSITY Sr # Major and Detailed Coverage Area
INC 161 , CPE 100 Computer Programming
Pointers & Arrays 1-d arrays & pointers 2-d arrays & pointers.
Strings (Continued) Chapter 13
© 2016 Pearson Education, Ltd. All rights reserved.
Lecture 8 String 1. Concept of strings String and pointers
A First Book of ANSI C Fourth Edition
CSE 303 Lecture 14 Strings in C
Module 2 Arrays and strings – example programs.
Strings A string is a sequence of characters treated as a group
Arrays in C.
Programming Languages and Paradigms
Programming and Data Structure
CS111 Computer Programming
C Stuff CS 2308.
INC 161 , CPE 100 Computer Programming
Strings A collection of characters taken as a set:
Chapter 9 - Formatted Input/Output
Lecture 11 Strings.
Chapter 7 Arrays PROGRAMMING IN ANSI C.
String What it is Why it’s useful
Strings Dr. Soha S. Zaghloul updated by Rasha ALEidan
Chapter 4 Managing Input and Output Operations
Homework Starting K&R Chapter 5 Good tutorial on pointers
ECE 103 Engineering Programming Chapter 25 C Strings, Part 1
Exercise Arrays.
Strings in C Array of characters is called a string.
Strings #include <stdio.h>
CS31 Discussion 1H Fall18: week 6
EECE.2160 ECE Application Programming
cout << str1;  pear
Dr. Khizar Hayat Associate Prof. of Computer Science
Introduction to Problem Solving and Programming
Presentation transcript:

Chapter 8 Character Arrays and Strings PROGRAMMING IN ANSI C

c[0]=72; c[1]=101; c[2]=c[3]=108; c[4]=111; 2/18/2019 Character Arrays In a character array, each element stores one character. e.g. char c[5]; c[0]='H'; c[1]='e'; c[2]=c[3]='l'; c[4]='o'; c[0] H c[1] e c[2] l c[3] c[4] o c[0]=72; c[1]=101; c[2]=c[3]=108; c[4]=111;

Character Arrays - Initialization 2/18/2019 Character Arrays - Initialization Like other type one-dimensional arrays, the character array can be initialized in the same way. e.g. char c[5] = { 'H', 'e', 'l', 'l', 'o' }; If the number of initializers is less than the declared size, the remaining elements are initialized to null character ('\0'). e.g. char c[6] = { 'H', 'e', 'l', 'l', 'o' }; c[0] H c[1] e c[2] l c[3] c[4] o c[5] \0 c[0] H c[1] e c[2] l c[3] c[4] o

Character Arrays - Initialization 2/18/2019 Character Arrays - Initialization Like other type one-dimensional arrays, the character array can be initialized in the same way. e.g. char c[5] = { 'H', 'e', 'l', 'l', 'o' }; If the number of initializers is more than the declared size, the complier will produce an error. e.g. char c[4] = { 'H', 'e', 'l', 'l', 'o' }; c[0] H c[1] e c[2] l c[3] c[4] o Error … : Too many initializers in function ...

Character Arrays - Initialization 2/18/2019 Character Arrays - Initialization Like other type one-dimensional arrays, the character array can be initialized in the same way. e.g. char c[5] = { 'H', 'e', 'l', 'l', 'o' }; If the number of initializers is equal to the declared size, the size may be omitted. e.g. char c[ ] = { 'H', 'e', 'l', 'l', 'o' }; c[0] H c[1] e c[2] l c[3] c[4] o

2/18/2019 Character Arrays The character array can be used as other type one-dimensional arrays. I am happy main() { char c[10] = { 'I', '', 'a', 'm', '', 'h', 'a', 'p', 'p', 'y' }; int i; for ( i = 0; i < 10; i++ ) printf ( "%c", c[i] ); }

Strings A string is a character array. 2/18/2019 Strings A string is a character array. char c[10] = { 'I', '', 'a', 'm', '', 'h', 'a', 'p', 'p', 'y' }; The actual length of the string is not always equal to the size of the character array. In fact, we often concern the actual length of a string rather than the size of a character array. char c[100] = { 'I', '', 'a', 'm', '', 'h', 'a', 'p', 'p', 'y' }; The size of the character array is 100, but the actual length of the string is only 10.

2/18/2019 Strings The array size is often much larger than the size of the string stored in the array. In order to represent the end of the string, the null character '\0' is used as the "end-of-string" marker. char c[5] = { 'B', 'o ', 'y' }; c[0] B c[1] o c[2] y c[3] \0 c[4] c[3] is the "end-of-string" marker '\0', so the elements before it compose the string, and the length of the string is 3.

2/18/2019 Strings Pay attention to the distinction of the null character '\0', and the blank space character '', and the figure character '0'. The ASCII value of '\0' is 0. It can't be displayed and acts as the "end-of-string" marker. The ASCII value of '' is 32. It can be outputted as a blank and occupy one place. The ASCII value of '0' is 48. It can be outputted as a figure.

2/18/2019 Strings When a string constant is stored in memory, it also uses the null character '\0' as the "end-of-string" marker. For example: When the string "Hello" is stored in memory, it requires 6 bytes storage, and the last byte is used to store the null character '\0'.

Strings - Initialization 2/18/2019 Strings - Initialization Using characters. char c[5] = { 'G', 'o ', 'o', 'd' }; Using string. char c[5] = { "Good" }; char c[5] = "Good"; char c[ ] = "Good"; c[0] G c[1] o c[2] c[3] d c[4] \0 Notice: The array c consists of 5 elements but not 4 elements! This declaration is equivalent to: char c[5] = "Good"; It differs with char c[4] = "Good";

Strings - Initialization 2/18/2019 Strings - Initialization The initialization of table of strings. char fruit[ ][7] = { "Apple", "Orange", "Grape", "Pear", "Peach"}; \0 h c a e P fruit[4] r fruit[3] p G fruit[2] g n O fruit[1] l A fruit[0]

Input and Output – %c abcde abcde _ abcdefg abcdef_ %c main() 2/18/2019 Input and Output – %c abcde abcde _ abcdefg abcdef_ %c main() { char str[6]; int i; for ( i = 0; i < 6; i++ ) scanf ( "%c", &str[i] ); printf ( "%c", str[i] ); }

Input and Output – %s abc abc_ str[0] a str[1] b str[2] c str[3] \0 2/18/2019 Input and Output – %s abc abc_ str[0] a str[1] b str[2] c str[3] \0 str[4] ? str[0] ? str[1] str[2] str[3] str[4] %s main() { char str[5]; scanf ( "%s", str ); printf ( "%s", str ); } str is the address of the string (character array), don't use &str. The number of the input characters should be less than 5. "blank space" or "tab" or "newline" marks the end of the input string. The "end-of string" marker '\0' is stored automatically. The string is outputted from the address str (the address of the string), and stopped when the element is the "end-of string" marker '\0'.

Input and Output – %s # a -> H e l o \0 = s " @ # a -> H e l o = 2/18/2019 Input and Output – %s # a -> H e l o \0 = s " @ # a -> H e l o = s \0 " @ # ê ¬ 7 $ f = s \0 " @ %s Hello#=s main() { char a[ ] = { 'H', 'e', 'l', 'l', 'o' }; printf ( "%s", a ); } Hello main() { char a[ ] = "Hello"; printf ( "%s", a ); }

Input and Output – %s # a -> H e l \0 = s " @ # a -> H e l o = s 2/18/2019 Input and Output – %s # a -> H e l \0 = s " @ # a -> H e l o = s \0 " @ # ê ¬ 7 $ f = s \0 " @ %s Hell main() { char a[5] = { 'H', 'e', 'l', 'l' }; printf ( "%s", a ); } Error … : Too many initializers in function ... Hello#=s main() { char a[5] = "Hello"; printf ( "%s", a ); } main() { char a[4] = "Hello"; printf ( "%s", a ); }

Input and Output – %s # a -> H e l \0 o ! " @ # ê ¬ 7 $ f = s \0 " 2/18/2019 Input and Output – %s # a -> H e l \0 o ! " @ # ê ¬ 7 $ f = s \0 " @ %s Hell main() { char a[ ] = {'H', 'e', 'l', 'l', '\0', 'o', '!', '\0'}; printf ( "%s", a ); } The output begins from the address "a" and ends when it encounters the first null character.

2/18/2019 The length of the input string must be less than the length of the array! Input and Output – %s address: a: ffd2, n: ffd6 a: ê¬7$, n: 1 Please input a string: abcd a: abcd, n: 0 address: a: ffd2, n: ffd6 a: ê¬7$, n: 1 Please input a string: abcde a: abcde, n: 101 address: a: ffd2, n: ffd6 a: ê¬7$, n: 1 Please input a string: abc a: abc, n: 1 # a -> 'ê' '¬' '7' '$' n -> 1 '*' 's' ']' '@' # a -> 'a' 'b' 'c' 'd' n -> 'e' \0 '*' 's' ']' '@' # a -> 'a' 'b' 'c' \0 n -> 1 '*' 's' ']' '@' # a -> 'a' 'b' 'c' 'd' n -> \0 '*' 's' ']' '@' %s main() { char a[4]; int n = 1; printf ( "address: a: %x, n: %x\n", a, &n ); printf ( "a: %s, n: %d\n", a, n ); printf ( "Please input a string:\n" ); scanf ( "%s", a ); printf ( "a: %s, n: %d", a, n ); }

"blank space" or "tab" or "newline" marks the end of the input string. 2/18/2019 Input and Output – %s How are you? a=How b=are c=you? %s main() { char a[15], b[5], c[5]; scanf ( "%s%s%s", a, b, c ); printf ( "a=%s\nb=%s\nc=%s\n", a, b, c ); } "blank space" or "tab" or "newline" marks the end of the input string. a b c \0 w o H e r a ? u y

   Input and Output – %s char s[100], c; int k; 2/18/2019 Input and Output – %s char s[100], c; int k; Question: We want to input a string "This is a string.". Can the following statements read in this string correctly? (A) scanf ( "%17s", s ); (B) for ( k = 0; k < 17; k++ ) s[k] = getchar(); (C) k = 0; while ( ( c = getchar() ) != '\n' ) s [k++] = c; s [k] = 0;   

Input and Output – puts( ) 2/18/2019 Input and Output – puts( ) How do you do? I'm Ok. Thank you. _ How do you do? _ puts( ) Form: puts (str) After it outputs the string, it moves the cursor to the next line automatically. main() { char c[ ] = "How do you do?"; puts ( c ); puts ( "I'm OK. Thank you." ); }

Input and Output – gets( ) 2/18/2019 Input and Output – gets( ) gets( ) Form: gets (str) It is used to read a line of text. Only the "newline" character marks the end of the input string. The "blank space" and "tab" will be read in as a character in the string. How are you? _ main() { char c[50]; gets ( c ); puts ( c ); }

String-Handling Functions – strcat( ) 2/18/2019 String-Handling Functions – strcat( ) strcat (str1, str2) Function: Concatenates 2 strings (str2 is appended to str1). Return value: The address of str1. str1 \0  w o H \0 e r a  w o H \0 e r a str2 How are are _ How are _ #include <string.h> main() { char str1[10]="How "; char str2[5]="are"; puts ( strcat ( str1,str2 ) ); puts ( str2 ); } #include <string.h> main() { char str1[10]="How "; char str2[5]="are"; strcat ( str1,str2 ); puts ( str1 ); puts ( str2 ); }

String-Handling Functions – strcat( ) 2/18/2019 String-Handling Functions – strcat( ) strcat (str1, str2) Function: Concatenates 2 strings (str2 is appended to str1). Return value: The address of str1. We can't use such statement to join 2 strings together: str1 = str1 + str2; str1 and str2 both are address values; str1 is an address constant, and it can't be assigned by any value again.

String-Handling Functions – strcpy( ) 2/18/2019 String-Handling Functions – strcpy( ) strcpy (str1, str2) Function: Copies one string (str2) over another (str1). Return value: The address of str1.

String-Handling Functions – strcpy( ) 2/18/2019 String-Handling Functions – strcpy( ) #include <string.h> main() { char tc[10]; char b[ ] = " "; char c[ ]= "C"; char t[ ] = "Turbo"; strcpy ( tc, t ); strcat ( tc, b ); strcat ( tc, c ); printf("%s\n", tc); } tc ! 9 y 8 \0 7 C 6  5 o 4 b 3 r 2 u 1 T ! 9 y 8 G 7 : 6 & 5 ( 4 @ 3 2 $ 1 ^ ! 9 y 8 G 7 \0 6  5 o 4 b 3 r 2 u 1 T ! 9 y 8 G 7 : 6 \0 5 o 4 b 3 r 2 u 1 T Turbo C \0 o b r u T C  c t

String-Handling Functions – strcpy( ) 2/18/2019 String-Handling Functions – strcpy( ) strcpy (str1, str2) Function: Copies one string (str2) over another (str1). Return value: The address of str1. We can't use an assignment statement to assign any string to a character array (expect the initialization). char str1[10] = "How ", str2[10]; str2 = "How "; str1 = str2; strcpy ( str1, str2 );  

String-Handling Functions – strcmp( ) 2/18/2019 String-Handling Functions – strcmp( ) strcmp (str1, str2) Function: Compares two strings. It compares the characters of st1 and str2 one by one. And it will stop when it finds the first different character or it encounters one null character. Return value: When the function stops the comparison, the difference of the ASCII value between the current character of str1 and that of str2. strcmp ( "A", "B" ) strcmp ( "a", "A" ) strcmp ( "ABC", "AB" ) strcmp ( "computer", "compare" ) strcmp ( "36", "3654" ) => 'A' – 'B' => -1 => 'a' – 'A' => 32 => 'C' – '\0' = 67 => 'u' – 'a' = 20 => '\0' – '5' = -53

String-Handling Functions – strcmp( ) 2/18/2019 String-Handling Functions – strcmp( ) strcmp (str1, str2) We can't use "==" operator to compare two strings. while ( st1 == str2 ) ... change to: while ( strcmp(str1, str2) == 0 ) or while ( ! strcmp(str1, str2) )

String-Handling Functions – strlen( ) 2/18/2019 String-Handling Functions – strlen( ) strlen (str) Function: Return the length of the string (the number of the characters of str except the null character). For these following declarations, what is the value of the function strlen(s)? (1) char s[10] = {'A', '\0', 'B', 'C', '\0', 'D'}; (2) char s[ ]="\t\b\\\0will\n"; (3) char s[ ]="\x69\082\n"; 1 ("A") 3 ("\t\b\\") 1 ("i")

2/18/2019 String - Program 1 Write a program to calculate the length of a string. Don't use the function strlen(). Step 1: Declare a character array s[100]; Step 2: Read in a string. Step 3: Calculate the number of the characters before the first null character in s. It is the length of s. Step 4: Output the value of the number.

String - Program 1 Please input the string: How are you? 2/18/2019 String - Program 1 Please input the string: How are you? The length of string is 3. Please input the string: Hello The length of string is 5. main() { char s[100]; int i = 0, slen = 0; printf ( "Pleas input the string:\n" ); scanf ( "%s", s ); while ( s[i] != '\0' ) { slen ++; i++; } printf ( "The length of string is: %d\n", slen ); while ( s[i] != 0 ) while ( s[i] )

2/18/2019 String - Program 2 \0 z y x b a d c \0 z y x d c b a Write a program to concatenate 2 strings. Don't use the function strcat(). Step 1: Declare two character arrays a[100], b[50]; Step 2: Read two strings into arrays a and b. Step 3: Begin with the null character of the array a to copy all the characters before the null character of array b into array a. Step 4: Output the arrays a and b.

String - Program 2 main() { char a[100], b[50]; int i = 0, j = 0; 2/18/2019 String - Program 2 main() { char a[100], b[50]; int i = 0, j = 0; printf ( "Pleas input 2 strings:\n" ); scanf ( "%s%s", a, b ); while ( a[i] != 0 ) i++; while ( b[j] != 0 ) { a[i] = b[j]; i++; j++; } a[i] = 0; printf ( "a: %s\nb: %s\n", a, b ); Please input 2 strings: Good boy! a: Goodboy! b: boy!

2/18/2019 String - Program 3 Write a program to reverse the characters of a string. Step 1: Declare a character arrays a[50]; Step 2: Read a string into a. Step 3: Get the subscript of the null character of the array a, and assign it to variable i. Step 4: for ( j = 0; j < i; j++, i-- ) exchange a[i] and a[j].

String - Program 3 main() { char a[30], ch; int i = 0, j = 0; 2/18/2019 String - Program 3 main() { char a[30], ch; int i = 0, j = 0; printf ( "Pleas input the string:\n" ); scanf ( "%s", a ); while ( a[i] != 0 ) i ++; i--; for ( j = 0; j < i; j++, i-- ) { ch = a[j]; a[j] = a[i]; a[i] = ch; } printf ( "%s\n", a ); Please input the string: abcd dcba j <= i / 2 a \0 d c b \0 a b c d \0 a c b d i j j i j i i

Homework Review Questions P243 2/18/2019 Homework Review Questions P243 8.1, 8.2 [except (h)], 8.6~8.10 (Write down in your exercise book) Programming Exercises