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.

Slides:



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

Strings Input/Output scanf and printf sscanf and sprintf gets and puts.
 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.
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)
 2000 Prentice Hall, Inc. All rights reserved Fundamentals of Strings and Characters String declarations –Declare as a character array or a variable.
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 9 Strings Instructor: Alkar / Demirer. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-2 Strings stringC implements the string data.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 8 - Characters and Strings Outline 8.1Introduction 8.2Fundamentals of Strings and Characters 8.3Character.
Chapter 10.
Chapter 8 Characters and Strings Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Fundamentals of Strings and Characters Characters.
N-1 University of Washington Computer Programming I Lecture 19: Strings © 2000 UW CSE.
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.
 2007 Pearson Education, Inc. All rights reserved C Characters and Strings.
EPSII 59:006 Spring Introduction Fundamentals of Strings and Characters Character Handling Library String Conversion Functions Standard Input/Output.
Introduction to C programming
C How to Program, 6/e © by Pearson Education, Inc. All Rights Reserved.
CHAPTER 8 CHARACTER AND STRINGS
CNG 140 C Programming (Lecture set 9) Spring Chapter 9 Character Strings.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 8 - Characters and Strings Outline 8.1Introduction 8.2Fundamentals of Strings and Characters 8.3Character.
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.
Characters and Strings File Processing Exercise C Programming:Part 3.
Chapter 8 Characters and Strings Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
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: Character and String CMPD144: Programming 1.
1 This chapter covers both string constants (or literals, as they're called in the C standard) and string variables, which can change during the execution.
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.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Pointers and Strings Outline 5.1 Introduction 5.2 Pointer Variable Declarations and Initialization.
 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];
Pointer Arithmetic (1) u When a pointer variable points to an array element, there is a meaning of adding or substracting an integer to/from the pointer.
Chapter 8 Characters and Strings. Objectives In this chapter, you will learn: –To be able to use the functions of the character handling library ( ctype).
C++ Programming Lecture 19 Strings The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI N305 Characters and Strings Functions.
Strings, Pointers and Tools
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.
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.
INC 161 , CPE 100 Computer Programming
C Characters and Strings
Fundamentals of Characters and Strings
A First Book of ANSI C Fourth Edition
CSE 303 Lecture 14 Strings in C
C Programming:Part 3 Characters and Strings File Processing Exercise.
Input/Output Input/Output operations are performed using input/output functions Common input/output functions are provided as part of C’s standard input/output.
INC 161 , CPE 100 Computer Programming
Lecture 11 Strings.
Strings #include <stdio.h>
Characters and Strings Functions
C Characters and Strings
Presentation transcript:

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 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.

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])... hi!\0?????? s [0] [1] [2] [3] [4] [5] [6] [7] [8] [9]

String Literals String literals are given as a string quoted by double quotes. – printf("Long long ago."); Initializing char array... – char s[10]="unix"; /* s[4] is '\0'; */ – char s[ ]="unix"; /* s has five elements */

Printing with printf ( ) Example: char str[ ] = "A message to display"; printf ("%s\n", str); printf expects to receive a string as an additional parameter when it sees %s in the format string – Can be from a character array. – Can be another literal string. – Can be from a character pointer (more on this later). 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. See example program 1

Printing with puts( ) The puts function is a much simpler output function than printf for string printing. Prototype of puts is defined in stdio.h int puts(const char * str) – 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\n"; puts(sentence); Prints out: The quick brown fox

Inputting Strings with gets( ) gets( ) gets a line from the standard input. The prototype is defined in stdio.h char *gets(char *str) – str is a pointer to the space where gets will store the line to, or a character array. – Returns NULL upon failure. Otherwise, it returns str. char your_line[100]; printf("Enter a line:\n"); gets(your_line); puts("Your input follows:\n"); puts(your_line); – You can overflow your string buffer, so be careful!

Inputting Strings with scanf ( ) To read a string include: – %s scans up to but not including the “next” white space character – %ns scans the next n characters or up to the next white space character, whichever comes first Example: scanf ("%s%s%s", s1, s2, s3); scanf ("%2s%2s%2s", s1, s2, s3); – Note: No ampersand(&) when inputting strings into character arrays! (We’ll explain why later …) Difference between gets – gets( ) read a line – scanf("%s",…) read up to the next space

The C String Library String functions are provided in an ANSI standard string library. – Access this through the include file: #include – Includes functions such as: Computing length of string Copying strings Concatenating strings – This library is guaranteed to be there in any ANSI standard implementation of C.

strlen strlen returns the length of a NULL terminated character string: size_t strlen (char * str) ; Defined in string.h size_t – A type defined in string.h that is equivalent to an unsigned int char *str – Points to a series of characters or is a character array ending with '\0' – The following code has a problem! char a[5]={‘a’, ’b’, ’c’, ’d’, ’e’}; strlen(a);

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) The return value also points at the destination.

strcat Included in string.h and comes in the form: char * strcat (char * str1, char * str2); Appends a copy of str2 to the end of str1 A pointer equal to str1 is returned 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.

Example See example program 3

Comparing Strings C strings can be compared for equality or inequality If they are equal - they are ASCII identical If they are unequal the comparison function will return an int that is interpreted as: < 0 : str1 is less than str2 0 : str1 is equal to str2 > 0 : str1 is greater than str2

strcmp Four basic comparison functions: int strcmp (char *str1, char *str2) ; Does an ASCII comparison one char at a time until a difference is found between two chars – Return value is as stated before If both strings reach a '\0' at the same time, they are considered equal. 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 – Also have strcasecmp() and strncasecmp() which do the same as above, but ignore case in letters.

Searching Strings (1) There are a number of searching functions: – char * strchr (char * str, int ch) ; strchr search str until ch is found or NULL character is found instead. If found, a (non-NULL) pointer to ch is returned. – Otherwise, NULL is returned instead. – You can determine its location (index) in the string by: Subtracting the value returned from the address of the start of the string – More pointer arithmetic … more on this later!

Example Example use of strchr: #include int main() { char ch='b', buf[80]; strcpy(buf, "The quick brown fox"); if (strchr(buf,ch) == NULL) printf ("The character %c was not found.\n",ch); else printf ("The character %c was found at position %d\n", ch, strchr(buf,ch)-buf+1); }

Searching Strings (2) Another string searching function: char * strstr (char * str, char * query) ; strstr searches str until query is found or a NULL character is found instead. If found, a (non-NULL) pointer to str is returned. – Otherwise, NULL is returned instead.

sprintf() #include int sprintf( char *s, const char *format, …); Instead of printing to the stdin with printf(…), sprintf prints to a string. Very useful for formatting a string, or when one needs to convert integers or floating point numbers to strings. There is also a sscanf for formatted input from a string in the same way scanf works.

Example #include int main() { char result[100]; sprintf(result, "%f", (float)17/37 ); if (strstr(result, "45") != NULL) printf("The digit sequence 45 is in 17 divided by 37. \n"); return 0; }

Converting Strings to Numbers (1) Contained in and are often used int atoi (char *ptr); – Takes a character string and converts it to an integer. – White space and + or - are OK. – Starts at beginning and continues until something non- convertible is encountered. Some examples: String Value returned "157"157 "-1.6"-1 "+50x"50 "twelve"0 "x506"0

Converting Strings to Numbers (2) long atol (char *ptr) ; – Same as atoi except it returns a long. double atof (char * str); – Handles digits 0-9. – A decimal point. – An exponent indicator (e or E). – If no characters are convertible a 0 is returned. Examples: – StringValue returned "12" "-0.123" "123E+3" "123.1e-5"