Lecture 11 Strings.

Slides:



Advertisements
Similar presentations
Strings Input/Output scanf and printf sscanf and sprintf gets and puts.
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 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.
ECE Application Programming Instructor: Dr. Michael Geiger Spring 2012 Lecture 31: PE5.
1 Introduction to Computing: Lecture 16 Character Strings Dr. Bekir KARLIK Yasar University Department of Computer Engineering
Searching and Sorting an Array 4 Searching and sorting are two fundamental algorithms often implemented with arrays –Search an array to determine the location.
1 Introduction to Computing Lecture 11 Character Strings Assist.Prof.Dr. Nükhet ÖZBEK Ege University Department of Electrical&Electronics Engineering
1 Strings ( מחרוזות ). 2 Agenda Definition and initialization Termination Input / Output String library.
N-1 University of Washington Computer Programming I Lecture 19: Strings © 2000 UW CSE.
To remind us We finished the last day by introducing If statements Their structure was:::::::::
C Programming Strings. Array of characters – most common type of array in C  Let’s make them easier for use Denote the end of array using a special character.
Strings. Sentences in English are implemented as strings in the C language. Computations involving strings are very common. E.g. – Is string_1 the same.
PRESENTED BY: ER. SUMANPREET KAUR LECTURER IN CE DEPTT. GPCG ASR.
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.
Introduction to C programming
Introduction to Programming Strings. 2 Introduction  Until now  We have seen strings in cout  Our old definition: string is a set of char between “”
Chapter 9 Character Strings 9.1 Character String Constants A character string constant is a sequence of characters enclosed in double quotation mark. Examples.
Lecture 22: Reviews for Exam 2. Functions Arrays Pointers Strings C Files.
Arrays II (Strings). Data types in C Integer : int i; Double: double x; Float: float y; Character: char ch; char cha[10], chb[]={‘h’,’e’,’l’,’l’,’o’};
Lecturer: Omid Jafarinezhad Sharif University of Technology Department of Computer Engineering 1 Fundamental of Programming (C) Lecture 6 Array and String.
Review of Lectures 12, 13, 14 -Functions -Arrays -Strings.
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.
CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 21 Thanks for Lecture Slides:
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.
String Array (Multidimensional Arrays) 1. A string array is a multidimensional array of strings. It is declared in the following syntax: char variable_name[No_of_strings][size_of_each_string];
Strings, Pointers and Tools
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.
DCT1063 Programming 2 CHAPTER 3 STRINGS Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
19-Feb-02 Sudeshna Sarkar, CSE, IIT Kharagpur1 Arrays, Pointers, Strings Lecture 18 19/2/2002.
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.
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.
MULTI-DIMENSION ARRAY STRING Computer Programming Asst. Prof. Dr. Choopan Rattanapoka and Asst. Prof. Dr. Suphot Chunwiphat.
Strings C supports strings using one-dimensional character arrays. A string is defined as a null-terminated character array. In C, a null is 0. You must.
1 Chapter 8 – Character Arrays and Strings Outline 8.1Introduction 8.2Declaring and Initializing String 8.3Input/output of strings 8.4String-handling Functions.
מערכים (arrays) 02 אוקטובר אוקטובר אוקטובר 1602 אוקטובר אוקטובר אוקטובר 1602 אוקטובר אוקטובר אוקטובר 16 Department.
Strings CSCI 112: Programming in C.
INC 161 , CPE 100 Computer Programming
ECE Application Programming
Strings (Continued) Chapter 13
Characters and Strings
© 2016 Pearson Education, Ltd. All rights reserved.
Lecture 8 String 1. Concept of strings String and pointers
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.
Character Strings Lesson Outline
מחרוזות קרן כליף.
CS111 Computer Programming
Strings.
CSI 121 Structured Programming Language Lecture 21 Character Strings
INC 161 , CPE 100 Computer Programming
Strings.
CprE 185: Intro to Problem Solving (using C)
Strings Dr. Soha S. Zaghloul updated by Rasha ALEidan
EECE.2160 ECE Application Programming
Chapter 8 Character Arrays and Strings
String manipulation string.h library
EECE.2160 ECE Application Programming
Introduction to Computer Organization & Systems
Strings Adapted from Dr. Mary Eberlein, UT Austin.
Strings #include <stdio.h>
Programming Strings.
CS-161 Computer Programming Lecture 15 & 16: Arrays II
Strings Adapted from Dr. Mary Eberlein, UT Austin.
C Characters and Strings
EECE.2160 ECE Application Programming
Introduction to Problem Solving and Programming
Presentation transcript:

Lecture 11 Strings

Introduction Until now Strings: printf("This printf("This We have seen strings in printf Our old definition: string is a set of char between “” printf("This printf("This is a string\n"); is %s\n", "a string\n"); Strings: An array of chars Terminated by the null char '\0'

Strings in C Since strings are array char str3[] = {'p', 'r', 'o', 'm', '\0'}; char char str1[8] = "program"; str2[] = "program"; 'p' 'r' 'o' 'g' 'a' 'm' '\0'

String Initializing char array ... char s[10] = "unix"; /* s[4] is '\0'; */ char s[ ] = "unix"; /* s has five elements */

Strings are Character Arrays Strings in C are simply arrays of characters Example: char s [10]; This is a ten (10) element array that can hold a character string consisting of  9 characters This is because C does not know where the end of an array is at run time By convention, C uses a NULL character '\0' to terminate all strings in its library functions For example: char str [10] = {'u', 'n', 'I', 'x', '\0'}; It’s the string terminator (not the size of the array) that determines the length of the string

Strings Each character has an integer representation a b c d e … … … … z 97 98 99 100 101 ………………………112 A B C D E … … … … Z 65 66 67 68 69 ……………………… 90 1 2 3 4 5 6 7 8 9 48 49 50 51 52 53 54 55 56 57 \0 \n 10

Accessing Individual Characters The first element of any array in C is at index 0. The second is at index 1, and so on ... char s[10]; s[0] = 'h'; s[1] = 'i’; s[2] = '!'; s[3] = '\0'; This notation can be used in all kinds of statements and expressions in C: For example: c = s[1]; if (s[0] == '-') … switch (s[1]) ... ? \0 ! i h [9] [8] [7] [6] [5] [4] [3] [2] [1] [0] s

Strings Characters can be interpreted as integers char c = ‘A’; printf(“%c \n”,c); prints A printf(“%d \n”,c); prints 65 Printf(“%c \n”,65);

Reading & Writing Strings printf can be used to print strings printf("program"); printf("%s", "program"); scanf can be used to read strings char str[200]; scanf("%s", str); Note: No ampersand(&) when inputting strings into character arrays! Initial white spaces are ignored Read until white space (which is replaced by \0) We must allocate sufficient size printf knows how much to print out because of the NULL character at the end of all strings When it finds a \0, it knows to stop

Example char str[11]="unix and c"; printf("%s", str); printf("\n"); printf(str); str[2]='I'; \0 c d n a x i u [10] [9] [8] [7] [6] [5] [4] [3] [2] [1] [0] str \0 c d a x i n u [10] [9] [8] [7] [6] [5] [4] [3] [2] [1] [0] str \0 c d a x I n u [10] [9] [8] [7] [6] [5] [4] [3] [2] [1] [0] str

Exercise Write a function to count the number of characters in a string. Idea: count the number of characters before \0 H e l l o \0

Solution

Exercise Write a function that prints a string in reverse Idea: find the end of the string and print the characters backwards. H e l l o \0 Output: olleH

Solution

Exercise Write a function that compares 2 strings S1 and S2 using lexicographic order. Idea: compare character by character Return a neg value if S1 < S2, 0 if S1 == S2 a pos value if S1 > S2 H e l l o \0 H e l o o \0 l < o in lexicographic order

Solution (incomplete)

Solution (complete)

Reading & Writing Strings (cont’d) puts(str)is very simple version of printf Can only be used to print strings Adds ‘\n’ to end of string Prototype of puts is defined in stdio.h This is more efficient than printf : because your program doesn't need to analyze the format string at run-time. For example: char sentence[] = "The quick brown fox"; puts(sentence); // printf("The quick brown fox\n");

Reading & Writing Strings (cont’d) gets(char str[]) can be used to read strings gets does not ignore the white spaces Read until \n

Difference between gets and scanf gets( ) read a line scanf("%s",…) read up to the next space char line[80]; char line[80]; gets(line); scanf("%[ ^\n]s", line); puts(line); printf(“%s\n", line);

String Library Access to string library by #include <string.h> Many functions to work with strings Find the length of string Compare strings Copy strings Search in strings  Concatenating strings

Length of String strlen(str): Length of string From start to first occurrence of the null char char char str[] = "This is test"; str1[10]={'a', 'b', '\0', 'c', '\0'}; strlen(str)  12 strlen(str1)  2

Compare Strings str1 and str2 are compared as follows Compare char by char from left to right until str1 and str2 has same chars. In the first different char If(char of str1 < char of str2)  str1 < str2 If (both string finish)  str1 = str2 strcmp(str1, str2):compare str1 and str2 If(str1 == str2)  return 0 If(str1 < str2)  return -1 If(str1 > str2)  return 1

Compare Strings: Examples char s1[] = "abc"; char s2[] = "abc"; i = strcmp(s1, s2); //i = 0 char s3[] = "abc"; char s4[] = "abx"; i = strcmp(s3, s4); //i = -1 char s5[] = "axc"; char s6[] = "abc"; i = strcmp(s5, s6); //i = 1 char s7[] = "ab"; char s8[] = "abc"; i = strcmp(s7, s8); //i = -1 char s9[] = "abc"; char s10[] = "aBc"; i = strcmp(s9, s10); //i = 1

Compare Strings strcmpi(str1, str2) Compares str1 and str2 similar to strcmp But ignores uppercase/lowercase difference char str1[]="ABC", str2[]="abC"; strcmpi(str1, str2)  0

strcmp Compares n chars of str1 and str2 int strncmp (char *str1, char * str2, size_t n); Compares n chars of str1 and str2 Continues until n chars are compared or The end of str1or str2 is encountered

Example char str1[] = "The first string."; char str2[] = "The second string."; printf("%d\n", strcmp(str1,str2) ); // -1 printf("%d\n", strncmp(str1,str2,4) ); // 0 // 'f' - 's' = -13 printf("%d\n", strncmp(str1,str2,5) ); // -13 If(str1 == str2) … // Syntax error in many c complier!

strcpy Copying a string comes in the form: char *strcpy (char * destination, char * source); A copy of source is made at destination source should be NULL terminated destination should have enough room (its length should be at least the size of source)

Copy Strings: Example char str1[] = "Test String"; char str2[20]; strcpy(str2, str1); printf("%s\n", str2); printf("%s\n", str1); Test String Test String

strcat Appends a copy of str2 to the end of str1 Concatenating two stings: char * strcat (char * str1, char * str2); Appends a copy of str2 to the end of str1 Ensure that str1 has sufficient space for the concatenated string! Array index out of range will be the most popular bug in your C programming career

Concatenate Strings: Example strcat(str2, str1); printf("%s\n", str2); char str1[] = "String"; char str2[20]= "Test "; Test String

Example

Common Bugs & Avoiding them Strings which are used as destination scanf, strcpy, …. Must be large enough Take care about the ‘\0’ You should never destroy it!

Quiz Write a program that reads a number between 1 and 999 from user and spells out it in English. For example: 453  Four hundred fifty three 37  Thirty seven 204  Two hundred four