Characters and Strings 4 Character constants (single quotes): –‘a’, ‘A’, ‘0’, ‘1’, ‘\n’, ‘\0’, … 4 String constants (double quotes): –“Mary had a little.

Slides:



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

 2003 Prentice Hall, Inc. All rights reserved Fundamentals of Characters and Strings Character constant –Integer value represented as character.
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.
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.
 2000 Prentice Hall, Inc. All rights reserved Fundamentals of Strings and Characters String declarations –Declare as a character array or a variable.
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.
Array_strcpy void array_strcpy(char dest[], char src[]) { int i = 0; while (src[i] != '\0') { dest[i] = src[i]; i++; } dest[i] = '\0'; }
Searching and Sorting an Array 4 Searching and sorting are two fundamental algorithms often implemented with arrays –Search an array to determine the location.
N-1 University of Washington Computer Programming I Lecture 19: Strings © 2000 UW CSE.
Introduction to Computers and Programming Class 22 Character Arrays (Strings) Professor Avi Rosenfeld.
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.
C-Strings Joe Meehean. C-style Strings String literals (e.g., “foo”) in C++ are stored as const char[] C-style strings characters (e.g., ‘f’) are stored.
Computer Science 210 Computer Organization Strings in C.
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 5 Arrays and Strings C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Introduction to C programming
Data Type string #include // C++ String class string str1, str2; // Default constructor cin >> str1 >> str2; cout
Chapter 9 Character Strings 9.1 Character String Constants A character string constant is a sequence of characters enclosed in double quotation mark. Examples.
Strlen() implementation /* strlen : return length of string s */ int strlen(char *s) { int n; for (n = 0 ; s[n] != ‘\0’ ; n++) ; return n; } /* strlen.
BBS514 Structured Programming (Yapısal Programlama)1 Character Processing, Strings and Pointers,
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT8: Characters and Strings CS2311 Computer Programming.
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.
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)
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’};
String functions+ string I.Mona Alshehri. String Functions: Header file:#include Function: Int strlen(char s[n]) Description Calculates the length of.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI C-Style Strings Strings and String Functions Dale Roberts, Lecturer.
Chapter 8 Strings. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-2 Strings stringC implements the string data structure using arrays of.
CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 21 Thanks for Lecture Slides:
COIT29222-Structured Programming Lecture Week 08  Reading: Textbook (4 th Ed.), Chapter 4 Textbook (6 th Ed.), Chapter 7 Study Guide Book 2, Module 11.
Strings Programming Applications. Strings in C C stores a string in a block of memory. The string is terminated by the \0 character:
Copyright ©: Nahrstedt, Angrave, Abdelzaher1 C Basics Tarek Abdelzaher and Vikram Adve.
CS 1430: Programming in C++ 1. Data Type string #include // C++ String class string str1, str2; // Default constructor cin >> str1 >> str2; cout
 2003 Prentice Hall, Inc. All rights reserved. 11 Fundamentals of Characters and Strings Character constant –Integer value of a character –Single quotes.
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.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI N305 Characters and Strings Functions.
Strings, Pointers and Tools
Strings, Slide Fundamental Programming Strings.
CMSC 104, Version 8/061L25Strings.ppt Strings Topics String Libraries String Operations Sample Program Reading Sections
ENEE150 – 0102 ANDREW GOFFIN Strings. Project 2 Flight Database 4 options:  Print flight  Print airport  Find non-stop flights  Find one-stop flights.
Chapter 9 Strings J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei University of Technology.
Principles of Programming Chapter 8: Character & String  In this chapter, you’ll learn about;  Fundamentals of Strings and Characters  The difference.
DCT1063 Programming 2 CHAPTER 3 STRINGS Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
Chapter 16 Pointers and Arrays Pointers and Arrays We've seen examples of both of these in our LC-3 programs; now we'll see them in C. Pointer Address.
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.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 230 Characters and Strings Dale Roberts, Lecturer Computer Science,
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.
Principles of Programming - NI Chapter 10: Character & String : In this chapter, you’ll learn about; Fundamentals of Strings and Characters The difference.
String in C++. 2 Using Strings in C++ Programs String library or provides functions to: - manipulate strings - compare strings - search strings ASCII.
Pointers & Arrays 1-d arrays & pointers 2-d arrays & pointers.
Arrays in C.
Strings.
Chapter 16 Pointers and Arrays
Strings What is a string? It is an array of characters terminated with
Chapter 8 Character Arrays and Strings
Strings #include <stdio.h>
Characters and Strings Functions
Introduction to Problem Solving and Programming
Presentation transcript:

Characters and Strings 4 Character constants (single quotes): –‘a’, ‘A’, ‘0’, ‘1’, ‘\n’, ‘\0’, … 4 String constants (double quotes): –“Mary had a little %c%c%c%c.\n” 4 Character variables: char va = ‘I’, vb = ‘a’, vc = ‘m’, vd = ‘b’; printf(“Mary had a little %c%c%c%c.\n”, va,vb, vc, vd); null

Strings –Strings: arrays of char char pet[5] = {‘l’,’a’,’m’,’b’}; printf(“Mary had a little %s.\n”, pet); –More accurate: null terminated array of char pet: ‘l’ ‘a’ ‘m’ ‘b’ ‘\0’ pet[0] pet[4]

Initializing Strings char pet[5] = {‘l’,’a’,’m’,’b’}; char pet[5]; pet[0] = ‘l’; pet[1] = ‘a’; pet[2] = ‘m’; pet[4] = ‘b’; pet[5] = ‘\0’; char pet[] = {‘l’,’a’,’m’,’b’}; But not: char pet[5]; pet = “lamb”; /* No array assignment in C */ all equivalent

Things You Can and Can’t Do –You can’t use = to assign one string variable to another (use library functions strcpy etc.) –You can’t use == to directly compare strings (use library functions strcmp etc.) –You can’t have a string as a function return type –You can directly scanf or printf strings (use %s)

Do-It-Yourself String Assignment char str[10], str[2] = “Saturday”; int i; /* What won’t work: str1 = str2 */ for (i = 0; str2[i] != ‘\0’; ++i) str[i] = str2[i]; str[i] = ‘\0’;

String Assignment with strcpy /* strcpy is defined in string.h: copy source string into dest, stopping at \0 */ void strcpy(char dest[], char source[]) { int j; for (j = 0; source[j] != ‘\0’; ++j) dest[j] = source[j]; dest[j] = ‘\0’; }

String Assignment: Dangers #include … char medium[] = “Four score and seven”; char big[1000]; char small[5]; strcpy(big,medium); strcpy(big,”Bob”); strcpy(small,big); strcpy(small,medium); /* Trouble! */

strcpy Results medium: Fourscore and seven \0 big: Four score and seven \0 ???… big: Bob \0 score and seven \0 ???… small: Bob \0? small: Four score and seven \0

String length: strlen /* Return the length of a string s, I.e. * number of characters before first ‘\0’ */ int strlen(char s[]) { int n = 0; while (s[n] != ‘\0’) n += 1; return(n); }

Length Examples #include /* defn of strlen, strcpy */ … char pet[] = “lamb”; int len1, len2, len3, len4, len5; len1 = strlen(pet); l a m b \0 len2 = strlen(“wolf”); w o l f \0 len3 = strlen(“”); \0 len4 = strlen(“Help\n”); H e l p \n \0 strcpy(pet, “cat”); len5 = strlen(pet); c a t \0 \0

Example Use of strlen #include /* defn of strlen, strcpy */ … if (strlen(medium)<=4) strcpy(small,medium); else printf(“String is too long to copy.\n”);

Safer (?) String Copy: strncpy /* strncpy is defined in string.h copy source string to dest, truncating if necessary */ void strncpy(char dest[], char source[], int destlen) { int j; for (j=0; j<destlen; j++) if (j <= strlen(source)) dest[j] = source[j]; else dest[j] = ‘\0’; }

strncpy Examples #include … char aug[] = “August”, month[10]; char aug_abbr[3], month_abbr[4]; strncpy(month,aug,10); /* OK */ strncpy(aug_abbr, aug, 3); /* OK? */ strcpy(month_abbr,aug_abbr); /* Trouble! */

strncpy Results aug A u g u s t \0 month A u g u s t \0 \0 \0 \0 aug_abbr A u $ #... month_abbr A u $ #...

Safer String Copy #include /* copy source string to dest if it fits */ void string_assign(char dest[], char source[], int destlen) { if (strlen(source)<destlen) strcpy(dest,source); else printf(“source string is too long to copy.\n”); }

String Concatenation #include … char str1[] = “lamb”, str2[] = “chop”; char str3[11]; strcpy(str3,str1); strcat(str3,str2);

strcat Results str1l a m b \0 str2c h o p \0 str3? ? ? ? ? ? ? ? ? ? ? str3l a m b \0 ? ? ? ? ? ? str3l a m b c h o p \0 ? ?

Comparing Strings –str_1 is less than str_2 if j is the first position where they differ and str_1[j]<str_2[j]. “lamb” is less than “wolf” j = 0, ‘l’ < ‘w’ “lamb” is less than “lamp” j = 3, ‘b’ < ‘p’ “lamb” is less than “lambchop” j = 4, ‘\0’ < ‘c’

String Comparison Errors str1=str2; /* Syntax error */ if (str1 == str2)… /* No syntax error, (almost surely a logic error */ if (str1 < str2)… /* Ditto */

Correct String Comparison /* function strcmp in */ int strcmp(char str_1[], char str_2[]): The integer returned is: negative if str_1 is less than str_2 zeroif str_1 equals str_2 positive if str_2 less than str_1 Common errors: strcmp is not a Boolean function!

String Input and Output –scanf with “%s” Skips initial whitespace Inserts ‘\0’ at next whitespace Danger: no length check –a malicious user could cause harm char in_string[10]; scanf(“%s”, in_string); printf with “%s” no &

Do-It-Yourself Whole Line Input With Line Checking char c line[LENGTH + 1]; int j; scanf(“%c”,&c); for (j=0; j<LENGTH+1 && c!= ‘\n’; j++) { line[j]=c; scanf(“%c”,&c); } if (j<LENGTH+1) line[j]=‘\0’; else printf(“Line too long.\n”);

Arrays of Strings char month[12][10] = { “January”, “February”, … “September”, /* Longest month: 9 letters */ … “December”}; printf(“%s is hot\n”, month[7]); /* August */

Reading and Printing Strings char name[NUM_NAMES][MAX_NAME+1}; int age[NUM_NAMES],j; for (j=0; j<NUM_NAMES; j++) { scanf(“%s %d”, name[j], &age[j]); printf(“%s %d\n”, name[j], age[j]); } no &

Other Functions in 4 Strcat, strncat concatenation 4 strcmp, strncmpcomparison 4 strtod,strtol,strtoulconversion 4 Many others - see Table 9.1 and Appendix B 4 Related useful functions in operations on a single char: convert case, check category, etc.

Strings Summary 4 Definition: Null-terminated array of char 4 A convention, not a first-class citizen –E.g., no string assignment or compare 4 library functions –Assignment: strcpy, strncpy –Length: strlen (length of contents, not container!) –scanf/printf: %s 4 Major Pitfall: overrunning allowed length