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,

Slides:



Advertisements
Similar presentations
Chapter 9 Strings. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 Learning Objectives An Array Type for Strings C-Strings Character.
Advertisements

Copyright © 2002 Pearson Education, Inc. Slide 1.
Introduction to C Programming
 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 snprintf() function.
Lecture 9. Lecture 9: Outline Strings [Kochan, chap. 10] –Character Arrays/ Character Strings –Initializing Character Strings. The null string. –Escape.
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.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 8- 1 Overview 8.1 An Array Type for Strings 8.2 The Standard string.
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.
CS31: Introduction to Computer Science I Discussion 1A 5/7/2010 Sungwon Yang
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.
Chapter 9: Arrays and Strings
C-strings Array with base type char One character per indexed variable
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.
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.
ACS 168 Structured Programming Using the Computer Spring 2002 Joaquin Vila Prepared by Shirley White.
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.
1 Data Structures A Data Structure is an arrangement of data in memory. A Data Structure is an arrangement of data in memory.  The purpose is to map real.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 8 - Characters and Strings Outline 8.1Introduction 8.2Fundamentals of Strings and Characters 8.3Character.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
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.
Strings in C are my friend, and they can be yours, too. An inspiring and epic tale by Erik Speyer, John Sullivan, and Dane Bennington.
9-1 Learning Objectives  An Array Type for Strings  C-Strings.
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’};
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:
Chapter 9 Strings. Learning Objectives An Array Type for Strings – C-Strings Character Manipulation Tools – Character I/O – get, put member functions.
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. 5.11Function Pointers Pointers to functions –Contain address of function –Similar to how array name is.
 2003 Prentice Hall, Inc. All rights reserved. 11 Fundamentals of Characters and Strings Character constant –Integer value of a character –Single quotes.
C/C++ Basics (VI) Strings and Vectors Berlin Chen 2003 Textbook: 1. Walter Savitch, “Absolute C++,” Addison Wesley, 2002 開發代理 2. Walter Savitch, “Problem.
An Array Type For Strings. Two ways to represent strings – i.e. “Hello” cstring An array with base type char Older way of processing strings Null character.
UniMAP SEM I - 09/10EKT 120 Computer Programming1 Lecture 8 – Arrays (2) & Strings.
C++ Programming Lecture 19 Strings The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
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.
DCT1063 Programming 2 CHAPTER 3 STRINGS Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
Copyright © 2002 Pearson Education, Inc. Slide 1.
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.
Slide 1 Chapter 9 Strings. Slide 2 Learning Objectives  An Array Type for Strings  C-Strings  Character Manipulation Tools  Character I/O  get, put.
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.
Fundamentals of Characters and Strings
Chapter 9 Strings Copyright © 2016 Pearson, Inc. All rights reserved.
Strings A string is a sequence of characters treated as a group
Pointers and Pointer-Based Strings
Week 9 – Lesson 1 Arrays – Character Strings
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.
Chapter 9 Strings Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
CPS120: Introduction to Computer Science
Presentation transcript:

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, declare a char array, e.g. char s[10]; Declares a c-string variable to hold up to 9 characters + one null character C-strings

String Variable Typically ‘partially-filled’ array – Declare large enough to hold max-size string, including the null character. A standard array: char s[10]; – If s contains string “Hi Mom!”, it will be stored as:

String Initialization Can initialize string: char myMessage[20] = "C is fun!"; Need not fill the entire array Initialization places '\0' at the end

String Initialization Can omit array-size: char shortString[] = "abc"; Automatically makes size one more than the length of the quoted string NOT the same as: char shortString[] = {'a', 'b', 'c'}; IS the same as: char shortString[] = {'a', 'b', 'c', '\0'};

Accessing elements of a string A string IS an array; therefore, Can access indexed variables of: char ourString[7] = "Hello"; ourString[0] is 'H' ourString[1] is 'e' ourString[2] is 'l' ourString[3] is 'l' ourString[4] is 'o'; ourString[5] is ‘\0’ ourString[6] is unknown

String Index Manipulation Can manipulate indexed variables char happyString[7] = "DoBeDo"; happyString[6] = 'Z'; Be careful! Here, ‘\0’ (null) was overwritten by a ‘Z’! If null is overwritten, string no longer ‘acts’ like a string! Unpredictable results!

String Input - fgets char *fgets (char * strPtr, int size, FILE *fp) – Inputs characters from the specified file pointer through \n or until specifed size is reached – Puts newline (\n) in the string if size not reached!!! – Appends \0 at the end of the string – If successful, returns the string – Example for stdin: const int MAX_LINE = 100; char lineIn[MAX_LINE+2]; // allow for \n and \0 fgets(lineIn, MAX_LINE, stdin);

String Output - fputs int fputs (const char *strPtr, FILE *fp) Takes a null-terminated string from memory and writes it to the specified file pointer Drops \0 Programmer's responsibility: Make sure the newline is present at the appropriate place(s) Example for stdout: char lineout[100] = "Hello!\n"; fputs(lineout, stdout);

Recall that a "C-string" is an array of characters whose logical end is denoted by a zero valued byte. The C standard library has a number of functions designed to work with C strings. The strtol() function is one of them. You can see most of them on a Linux system via the command: man string stpcpy, strcasecmp, strcat, strchr, strcmp, strcoll, strcpy, strcspn, strdup, strfry, strlen, strncat, strncmp, strncpy, strncasecmp, strpbrk, strrchr, strsep, strspn, strstr, strtok, strxfrm, index, rindex - string operations Use of pointers in processing C-strings.

= with strings strings are not like other variables – Cannot assign or compare: char aString[10]; aString = "Hello"; // ILLEGAL Can ONLY use ‘=‘ at declaration of string! – Must use library function for assignment: strcpy(astring, "Hello"); Built-in function (in ) Sets value of aString equal to "Hello" NO checks for size! – Up to programmer, just like other arrays!

== with strings Cannot use operator == char aString[10] = "Hello"; char anotherString[10] = "Goodbye"; if(aString == another String) // NOT allowed Must use strcmp library function to compare: if(strcmp(aString, another String)) printf("Strings NOT the same.\n"); else printf("Strings are the same.\n");

string Functions: strlen() String length Often useful to know the length of a string: char myString[10] = "dobedo"; printf("length = %d\n", strlen(myString)) – Returns number of characters Not including null character – Result here: 6

string Functions: strcat() String concatenate char stringVar[20] = "The rain"; strcat(stringVar, "in Spain"); Note result: stringVar now contains The rainin Spain Be careful! Incorporate spaces as needed!

string Functions In the following example, we will see how strcpy might be implemented. Its prototype is shown below. char *strcpy(char *s1, const char *s2);

The name zstrcpy s used to avoid potential nastygrams and name conflicts with the “real” strcpy. /* zstrcpy.c */ #include /* Prototype: char *zstrcpy(char *dst, char *src); where "dst" is a pointer to the location that the string is to be copied to, "src" is a pointer to the location that the string is copied from. */ An implementation of strcpy

char *zstrcpy(char *dst, char *src) { /* pointer to destination string */ /* pointer to source string */ char *dststart = dst; /* Remember start of destination string */ /* Copy characters from source to destination */ while (*src != '\0') { *dst = *src; dst++; src++; } *dst = *src; /* Copy null character */ return(dststart); } /* End zstrcpy */ An Implementation of strcpy

It is possible to shrink and obfuscate the code in an attempt to demonstrate ones C language machismo. This approach produces code that is difficult to read, painful to maintain, but may (or may not) produce a trivial improvement in performance. When tempted, just say no! /* zstrcpy.c */ #include /* Prototype: Short, less readable version. char *zstrcpy(char *dst, char *src); where "dst" is a pointer to the location that the string is to be copied to, "src" is a pointer to the location that the string is copied from. */ An alternative implementation

char *zstrcpy(char *dst, char *src) { /* dst - pointer to destination string */ /* src - pointer to source string */ char *dststart = dst; /* Copy characters from source to destination */ while (*src++ = *dst++) != '\0') { } return(dststart); } /* End zstrcpy */ An alternative implementation (cont'd)

We will explore the use of separately compiled modules later in the semester, but for now we’ll consider some simple cases. The nice thing about functions like zstrcpy() is that they can be used by multiple programs. For this to be convenient, we do not want to have to include the source code for zstrcpy() in every program we write that will use it. /* zstrtest.c */ #include Separately compiled modules

/* Prototype statement for zstrcpy() */ char *zstrcpy(char *s1, char *s2); /* Test program */ int main() { char *string1 = "This is a test string"; char *string2; string2 = (char *) malloc(strlen(string1)+1); zstrcpy(string2, string1); printf("Copied string: \"%s\"\n", string2); exit(0); } Separately compiled modules

Note that this program calls the zstrcpy() function. The prototype statement at the head of the main program (highlighted in red) is provided so that the compiler will know what the type of the zstrcpy() function is and what its parameters are. One way to compile and run this program is the following command line: gcc –o zstrtest –g –Wall zstrtest.c zstrcpy.c Note that both source files are specified, which means that both source files will be compiled to build the final executable program “zstrtest”. Separately compiled modules

Also note in this program the use of the statement #include This was necessary because the main program calls the string function "strlen()", and its prototype statement is in the include "string.h". For any given C function you can determine which include files are needed by entering a command, e.g. man strlen. This produces the "man" page description of the function which includes the list of include files that must be specified. Separately compiled modules