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.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

 A string is an array of characters.  Strings must have a 0 or null character after the last character to show where the string ends.  The null character.
Strings string.h library. String Library Functions Dr. Sadık EşmelioğluCENG 1142 NameDescription strlen return the length of string not counting \0 strcopy.
C Characters & Strings Character Review Character Handling Library Initialization String Conversion Functions String Handling Library Standard Input/Output.
Strings.
1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
Lecture 09 Strings, IDEs. METU Dept. of Computer Eng. Summer 2002 Ceng230 - Section 01 Introduction To C Programming by Ahmet Sacan Mon July 29, 2002.
Character String Manipulation. Overview Character string functions sscanf() function sprintf() function.
Character String Manipulation. Overview Character string functions sscanf() function snprintf() function.
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.
Strings CS240 Dick Steflik. What is a string A null terminated array of characters: char thisIsAString[10]; \0 The “\0” (null character)
ECE Application Programming Instructor: Dr. Michael Geiger Spring 2012 Lecture 31: PE5.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Characters and Strings.
Current Assignments Homework 5 will be available tomorrow and is due on Sunday. Arrays and Pointers Project 2 due tonight by midnight. Exam 2 on Monday.
Chapter Fourteen Strings Revisited. Strings A string is an array of characters A string is a pointer to a sequence of characters A string is a complete.
Chapter 9 Strings Instructor: Alkar / Demirer. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-2 Strings stringC implements the string data.
Searching and Sorting an Array 4 Searching and sorting are two fundamental algorithms often implemented with arrays –Search an array to determine the location.
Chapter 10.
Chapter 8 Characters and Strings Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
1 C-strings String = null-terminated array of characters The null character ('\0') specifies where the string terminates in memory. Example: The string.
C-Strings A C-string (also called a character string) is a sequence of contiguous characters in memory terminated by the NUL character '\0'. C-strings.
Strings String - a string is a series of characters treated as a unit. A C string is a variable-length array of characters that is delimited by the null.
C-strings Array with base type char One character per indexed variable
CS 161 Introduction to Programming and Problem Solving Chapter 13 Console IO Herbert G. Mayer, PSU Status 9/8/2014 Initial content copied verbatim from.
 2007 Pearson Education, Inc. All rights reserved C Characters and Strings.
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
Chapter 9 Character Strings 9.1 Character String Constants A character string constant is a sequence of characters enclosed in double quotation mark. Examples.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 8 - Characters and Strings Outline 8.1Introduction 8.2Fundamentals of Strings and Characters 8.3Character.
Array with base type char One character per indexed variable One extra character: '\0' Called ‘null character’ Delimiter of the string To declare a string,
CPT: Strings/ Computer Programming Techniques Semester 1, 1998 Objectives of these slides: –to discuss strings and their relationship.
CS 162 Introduction to Computer Science Chapter 17 C++ String Objects Herbert G. Mayer, PSU (Copied from Prof. Phillip Wong at PSU) Status 11/30/2014.
Character Arrays Based on the original work by Dr. Roger deBry Version 1.0.
APS105 Strings. C String storage We have used strings in printf format strings –Ex: printf(“Hello world\n”); “Hello world\n” is a string (of characters)
ECE 103 Engineering Programming Chapter 47 Dynamic Memory Alocation Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103.
Lecture 22: Reviews for Exam 2. Functions Arrays Pointers Strings C Files.
ECE 103 Engineering Programming Chapter 44 File I/O Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103 material developed.
Chapter 8 Characters and Strings Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
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’};
Chapter 8: Character and String CMPD144: Programming 1.
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.
1 Character Strings (Cstrings) Reference: CS215 textbook pages
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];
5.6 String Processing Part 2. Sprintf(destnvar,…..regularprintf) Write formatted data to string Same as printf except the output is put in variable. A.
Slides from Shane Griffith (TA and guest instructor in Fall 2008) CprE 185: Intro to Problem Solving.
Strings, Pointers and Tools
CMSC 104, Version 8/061L25Strings.ppt Strings Topics String Libraries String Operations Sample Program Reading Sections
Principles of Programming Chapter 8: Character & String  In this chapter, you’ll learn about;  Fundamentals of Strings and Characters  The difference.
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
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.
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.
CSE 251 Dr. Charles B. Owen Programming in C1 Strings and File I/O.
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.
Strings CSCI 112: Programming in C.
C Characters and Strings
Lecture 8 String 1. Concept of strings String and pointers
CSE 303 Lecture 14 Strings in C
C-strings In general, a string is a series of characters treated as a unit. Practically all string implementations treat a string as a variable-length.
ECE 103 Engineering Programming Chapter 51 Random Numbers
ECE 103 Engineering Programming Chapter 25 C Strings, Part 1
Strings #include <stdio.h>
Presentation transcript:

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 developed by Professor Phillip PSU ECE

Syllabus String I/O Functions String Library Functions String to Number Conversion Arrays of Strings

2 String I/O Functions C has library functions to input and output strings Use #include In the following table, char * is a pointer to a character array --strictly speaking, to a char-- that contains the string String I/O Functions int printf( const char * fmt, … ) Prints formatted output to console int sprintf( char * s, const char * fmt, … ) Prints formatted output to string int puts( const char * s ) Prints string to console int scanf( const char * fmt, … ) Reads formatted input from console int fgets( const char * s, FILE * stream ) Reads string from input stream

3 printf() int printf( const char * format, …); Writes formatted output to the console:  Use the %s format specifier for strings  %s expects the address of a char array which contains a string Example: char name[] = "Jane Doe"; printf("[%s]\n", name ); → [Jane Doe] printf("[%s]\n", & name[0] ); → [Jane Doe] printf("[%s]\n", & name[5] ); → [Doe]

4 sprintf() int sprintf( char * s, const char * format, …); Performs a formatted print and saves it into a string  Works like printf except the output is stored in string s  Nothing is printed to the console Example: char str[50]; int x = 4; sprintf( str,"x=%d y=%f", x, 1.5f ); printf( "title = %s\n", str );

5 puts() int puts( const char * s ); Writes a string to the console  A newline '\n' is automatically printed at the end of the string Example: char name[] = "Jane Doe"; puts( name ); printf( "lives here.\n” ); Output: Jane Doe lives here.

6 scanf() int scanf( const char * format, …); Reads formatted input from the console  Use the %s format specifier for strings  %s expects the address of a char array  Only reads single “words” at a time (whitespace delimited) Example: char str[100];/* String storage */ scanf( "%s", str );/* str is address */ scanf( "%s", &str[0] ); // synonymous to str

7 scanf()  scanf skips whitespace( space, tab, newline) and then stores in str all characters up to the next whitespace  scanf automatically adds '\0' to the end of the array  It does not check for char array overflow. The array must be large enough to hold the expected string and the '\0’  Any unused text remains in the input stream Example: scanf( "%s", str1 ); User types in: Hello, Portland !!! scanf( "%s", str2 ); → str1 holds Hello, → str2 holds Portland

8 fgets() char * fgets( char * s, int m, FILE * stream); Reads a string from the input stream  For input from the console, use stdin for the stream  fgets reads input characters until one of these conditions is met: m – 1 characters are read '\n' (newline) is read End-of-file is detected  If successful, returns pointer to s  If end-of-file, returns NULL pointer

9 Example #define MAXLEN 80 char str[ MAXLEN ]; /* String storage */ if( fgets( str, MAXLEN, stdin ) != NULL ) { printf( "%s", str ); }else{ printf( "End of file\n” ); } //end if

10  If a newline is entered to signal the end of input, the '\n' character is also stored as part of string  fgets automatically terminates the string with '\0’ Example: fgets( str, 10, stdin ); Suppose the user types in: Jim May  printf( "[%s]", str ); → [Jim May ] str → 'J''i''m'' 'M''a''y''\n''\0' User types Enter key (newline)

11 Is there a simple way to get rid of the extraneous '\n' when using fgets ? This is one approach that works: fgets( s, MAXLEN, stdin ); if( strchr( s,'\n') != NULL ) s[ strlen(s) - 1 ] = '\0'; Caveat: The if check is necessary because a Ctrl-D terminates input without adding an extra '\n’ Warning:There is also a function; gets(). DO NOT USE IT!! gets() does not check for char array overflow

12 String Library Functions C has a library of string processing functions. Use #include In the following table: s is of type char * (pointer to char array) n is of type size_t (unsigned integer) cs and ct are of type const char * c is an int converted to char

13 Some Common string lib functions size_t strlen( cs ) return length of cs. char * strcpy( s, ct ) copy string ct to string s, including ‘\0’; return s. char * strncpy( s, ct, n ) copy at most n characters of string ct to s ; return s. Pad with ‘\0’s if ct has fewer than n characters. char * strcat( s, ct ) concatenate string ct to end of string s ; return s. char * strncat( s, ct, n ) concatenate at most n characters of string ct to string s, terminate s with ‘\0’; return s. int strcmp( cs, ct ) compare string cs to string ct ; return 0 if cs > ct. int strncmp( cs, ct, n ) compare at most n characters of string cs to string ct ; return 0 if cs > ct. char * strchr( cs, c ) return pointer to first occurrence of c in cs or NULL if not present char * strrchr( cs, c ) return pointer to last occurrence of c in cs or NULL if not present char * strstr( cs, ct ) return pointer to first occurrence of string ct in cs, or NULL if not present

14 strlen() size_t strlen( const char * s ); Determines the length of the string s.  The function counts the number of characters in the array.  The count starts at array index 0.  It continues counting until the first '\0' is found. ('\0' itself is not included in the string length.) Example: strlen("") → 0 char x[] = "Cat"; strlen(x) → 3 SL = strlen(" PSU Vikings") → 12

15 strcpy() char * strcpy( char * d, const char * s ); Copies contents of string s to string d  The terminating '\0' is also copied to d.  The contents of d are overwritten.  The address of string d is returned.  Strings cannot be copied using the = assignment operator. Use strcpy() instead. Example: char dst[20], src[] = "Hello"; strcpy( dst, "Siri” ); → dst holds Siri strcpy( dst, src ); → dst holds Hello

16 strcat() char * strcat( char * d, const char * s ); Concatenates contents of string s to string d  The contents of s are appended to the end of whatever is already in d  The original '\0' in d is deleted before appending happens  The address of string d is returned  Strings cannot be concatenated using the + operator in C. Use strcat() instead. Example: char dst[20] = "PSU", src[] = " rocks!"; strcat( dst, src ); → dst holds PSU rocks!

17 strcmp() int strcmp( const char * s, const char * t ); Compares contents of string s to string t  s and t are compared character by character  Returns zero (0) if the strings are identical positive number if s is lexically greater than t negative number if t is lexically greater than s  Strings cannot be compared using a relational operator. Use strcmp() instead Example: char s1[5] = "PSU", s2[10] = "OSU"; strcmp( s1, s2 ); → returns 1 strcmp( s2, s1 ); → returns -1

18 Example: char a[10], b[10];/* Two strings */ strcpy( a, "Star” );/* a: Star */ strcpy( b, a );/* b: Star */ strcat( a, " Trek” );/* a: Star Trek */ strcat( b, " Wars” );/* b: Star Wars */ if( strlen(a) > 0 && strlen(b) > 0 ) if( strcmp( a, b ) == 0 ) printf( "You're kidding, right?\n” ); else if( strcmp(a,b) < 0 ) printf( "Trekker!\n” );

19 strchr() char * strchr( const char * s, int c ); Finds position of character c within string s.  If c is found, returns pointer to first occurrence of c in s. If c is not found, returns NULL pointer. Example: char s[] = "PSU OSU"; strchr( s, 'A’ ); → returns NULL p = strchr( s, 'U’ ); → returns pointer to first U

20 strchr() char * strstr( const char * s, const char * t ); Finds position of string t within string s.  If t is found, returns pointer to first occurrence of t in s. If t is not found, returns NULL pointer. Example: char s[] = "PSU OSU"; strstr( s, "A” ); → returns NULL p = strstr( s, "U O” ); → returns ptr to location

21 String to Number Conversion Use #include Conversion functions (partial list) Example: double x; char numstr[] = "12.75 HI"; x = atof( numstr ); → x contains x = atof( "HI 12.75” ); → x contains 0.0 printf( "%d\n", atoi( numstr ) ); → displays 12 double atof( const char * s ) Converts s to a number of type double int atoi( const char * s ) Converts s to a number of type int long atol( const char * s ) Converts s to a number of type long int

22 Array of Strings An array of strings (“string array”) is a 2-D array Each row represents a separate string When declaring the array, the number of columns must be large enough to hold the largest expected string An individual string within the array can be accessed by using just the row index

23 Example: /* 4 strings of up to 10 chars each */ char s[4][10]; strcpy( s[0], "Doe, Jane” ); strcpy( s[3], "Rand, Bob” ); /* Assume user enters: Li, Joe  */ fgets( s[1], 10, stdin ); /* Assume user enters: Li, Joe  */ scanf( "%s", s[2] ); printf( "%s\n", s[0] ); /* Doe, Jane */ printf( "%s\n", &s[0][5] ); /* Jane */ printf( "%c\n", s[3][6] ); /* B */

24 Example: (continued from previous page) s is the name for the entire array of strings. s[i] is the address of the i-th string in the array. s[i][j] is j-th character of the i-th string. s[i] is equivalent to &s[i][0]. s[3] → 'R''a''n''d'','' 'B'o''b''\0' length = 9 s[2] → 'L''i'',''\0' length = 3 s[1] → 'L''i'','' 'J''o''e''\n''\0' length = s[0] → 'D''o''e'','' 'J''a''n''e''\0' length = 9

25 Example: Write a string length function using arrays #include /* Function returns the length of a string */ Int str_len( const char s[]) { // str_len int k = 0; /* Array index for string */ while( s[k] != '\0') /* Look for string terminator */ k++; return k; /* k is also the length */ } //end str_len int main( void ) { // main char a[] = "Hello!"; printf( "String length is %d.\n", str_len(a) ); return 0; } //end main

26 Example: Write a string copy function using arrays /* String copy: source is ct, destination is s */ char * str_cpy( char s[], const char ct[] ) { int k = 0; /* Array index for string */ while( ct[k] != '\0’ ) { /* Look string terminator */ s[k] = ct[k]; /* Copy single character at a time */ k++; } //end while s[k] = '\0'; /* Add string terminator to destination */ return s; /* s by itself is an address */ } //end str_cpy