Strings in C Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition, by Kernighan.

Slides:



Advertisements
Similar presentations
1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
Advertisements

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.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Characters and Strings.
Pointer applications. Arrays and pointers Name of an array is a pointer constant to the first element whose value cannot be changed Address and name refer.
Kernighan/Ritchie: Kelley/Pohl:
Strings, Arrays, and Pointers CS-2303, C-Term Strings, Arrays, and Pointers CS-2303 System Programming Concepts (Slides include materials from The.
Differences between Java and C CS-2303, C-Term Differences between Java and C CS-2303, System Programming Concepts (Slides include materials from.
Strings, Arrays, and Pointers CS-2301 D-term Strings, Arrays, and Pointers CS-2301 System Programming C-term 2009 (Slides include materials from.
More on Numerical Computation CS-2301 B-term More on Numerical Computation CS-2301, System Programming for Non-majors (Slides include materials from.
1 CSE 303 Lecture 11 Heap memory allocation ( malloc, free ) reading: Programming in C Ch. 11, 17 slides created by Marty Stepp
Strings, Arrays, and Pointers CS-2301, B-Term Strings, Arrays, and Pointers CS-2301, System Programming for Non-Majors (Slides include materials.
CS-2303 System Programming Concepts
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.
C Programming Tutorial – Part I CS Introduction to Operating Systems.
Pointers, Heap Memory Rudra Dutta CSC Spring 2007, Section 001.
 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.
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)
Current Assignments Start Reading Chapter 6 Project 3 – Due Thursday, July 24 Contact List Program Homework 6 – Due Sunday, July 20 First part easy true/false.
Strings Programming Applications. Strings in C C stores a string in a block of memory. The string is terminated by the \0 character:
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
C Primer Session – 1/25/01 Outline Hello World Command Line Arguments Bit-wise Operators Dynamic Memory / Pointers Function Parameters Structures.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
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.
Chapter 5 Pointers and Arrays Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information Engineering Da-Yeh.
“Success consists of going from failure to failure without loss of enthusiasm.” Winston Churchill.
1 Binghamton University Exam 1 Review CS Binghamton University Birds eye view -- Topics Information Representation Bit-level manipulations Integer.
EGR 2261 Unit 11 Pointers and Dynamic Variables
Stack and Heap Memory Stack resident variables include:
Computer Organization and Design Pointers, Arrays and Strings in C
Pointers & Arrays 1-d arrays & pointers 2-d arrays & pointers.
Strings, Arrays, and Pointers
A bit of C programming Lecture 3 Uli Raich.
C Characters and Strings
C Programming Tutorial – Part I
Command Line Arguments
CSE 303 Concepts and Tools for Software Development
A First Book of ANSI C Fourth Edition
Computer Science 210 Computer Organization
Arrays in C.
Programming in C Input / Output.
Computer Science 210 Computer Organization
Programming in C Input / Output.
Strings.
Pointers Department of Computer Science-BGU יום רביעי 21 נובמבר 2018.
More about Numerical Computation
Pointers, Dynamic Data, and Reference Types
Memory Allocation CS 217.
Strings and Streams Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
Classes, Constructors, etc., in C++
Dynamic Memory Allocation (and Multi-Dimensional Arrays)
Structures, Unions, and Typedefs
Arrays and Pointers in C & C++
Linked Lists in C and C++
Programming Assignment #1 12-Month Calendar—
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.
Symbolic Constants in C
Recursion and Implementation of Functions
Accessing Files in C Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
Programming Assignment #5
Differences between Java and C
Chapter 16 Pointers and Arrays
Your first C and C++ programs
Operator Overloading Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
Strings Adapted from Dr. Mary Eberlein, UT Austin.
A Deeper Look at Classes
Strings Adapted from Dr. Mary Eberlein, UT Austin.
15213 C Primer 17 September 2002.
SPL – PS2 C++ Memory Handling.
Presentation transcript:

Strings in C Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition, by Kernighan and Ritchie, Absolute C++, by Walter Savitch, The C++ Programming Language, Special Edition, by Bjarne Stroustrup, and from C: How to Program, 5th and 6th editions, by Deitel and Deitel) CS-2303, A-Term 2012 Strings in C

Reading Assignment Kernighan & Ritchie, Chapter 5 All the way through! Study §5.5 in detail — pages 104-107 Character pointer and functions You will use these all the time! Study §5.10 — pages 114-118 Command line arguments You will use these a lot! Applicable also to C++ (Skip ahead) CS-2303, A-Term 2012 Strings in C

Review Array – a set of elements all of the same type stored contiguously in memory – e.g., int A[25]; // 25 integers struct Str B[15]; /* 15 objects of type struct Str */ double C[]; /* indeterminate # of doubles */ Pointer – a variable whose value is the location of some other object float *p; // pointer to a float CS-2303, A-Term 2012 Strings in C

Review (continued) int A[25]; // 25 integers Type of A[i] is int (for all i). Type of A is int * const I.e., constant pointer to int CS-2303, A-Term 2012 Strings in C

Summary Arrays and pointers are closely related Let int A[25]; int *p; int i, j; Let p = A; Then p points to A[0] p + i points to A[i] &A[j] == p+j *(p+j) is the same as A[j] CS-2303, A-Term 2012 Strings in C

Summary (continued) If void f(int A[], int arraySize); Then f(&B[i], bSize-i) calls f with subarray of B as argument Starting at element i, continuing for bSize-i elements CS-2303, A-Term 2012 Strings in C

Review (concluded) and void f(int *A, int arraySize); are identical! Most C programmers use pointer notation rather than array notation In these kinds of situations CS-2303, A-Term 2012 Strings in C

Additional Notes A pointer is not an integer … Not necessarily the same size May not be assigned to each other … except for value of zero! Called NULL in C; defined in <stdio.h> Means “pointer to nowhere” void * is a pointer to no type at all May be assigned to any pointer type Any pointer type may be assigned to void * CS-2303, A-Term 2012 Strings in C

Questions? CS-2303, A-Term 2012 Strings in C

C99 & C++ introduce a new data type called wchar for international text Characters in C char is a one-byte data type capable of holding a character (mostly printable) Treated as an arithmetic integer type (Usually) unsigned May be used in arithmetic expressions Add, subtract, multiply, divide, etc. Character constants 'a', 'b', 'c', …'z', '0', '1', … '9', '+', '-', '=', '!', '~', etc, '\n', '\t', '\0', etc. A-Z, a-z, 0-9 are in order, so that arithmetic can be done CS-2303, A-Term 2012 Strings in C

Strings in C Definition:– A string is a character array ending in the null character '\0' — i.e., char s[256]; char t[] = "This is an initialized string!"; char *u = "This is another string!"; String constants are in double quotes "like this" May contain any characters Including \" and \' — see p. 38, 193 of K&R String constants may not span lines in code However, they may be concatenated — e.g., "Hello, " "World!\n" is the same as "Hello, World!\n" CS-2303, A-Term 2012 Strings in C

Strings in C (continued) Let char *u = "This is another string!"; Then u[0] == 'T' u[1] == 'h' u[2] == 'i' … u[20] == ‘n' u[21] == 'g' u[22] == '!' u[23] == '\0' CS-2303, A-Term 2012 Strings in C

Support for Strings in C Most string manipulation is done through functions in <string.h> String functions depend upon final '\0' So you don’t have to count the characters! Examples:– int strlen(char *s) – returns length of string Excluding final '\0' char* strcpy(char *s, char *ct) – Copies string ct to string s, return s s must be big enough to hold contents of ct ct may be smaller than s CS-2303, A-Term 2012 Strings in C

Additional String Functions int strcmp(char *s, char *t) lexically compares s and t, returns <0 if s < t, >0 if s > t, and zero if s and t are identical K&R p. 106 for exact details expressed in code char* strcat(char *s, char *ct) Concatenates string ct to onto end of string s, returns s s must be big enough to hold contents of both strings! Other string functions strchr(), strrchr(), strspn(), strcspn() strpbrk(), strstr(), strtok(), … See K&R pp. 105-106 for various implementations §B.3 for complete list and specifications CS-2303, A-Term 2012 Strings in C

Character functions in C See <ctype.h> These return either 0 (i.e., false) or 1 (i.e., true) int isdigit(int c) int isalpha(int c) int isalnum(int c) int isxdigit(int c) int islower(int c) int isupper(int c) int isspace(int c) int iscntrl(int c) int ispunct(int c) int isprint(int c) int isgraph(int c) These change case (if appropriate) and return characters int toupper(int c) int tolower(int c) CS-2303, A-Term 2012 Strings in C

String Conversion Functions in C See <stdlib.h> K&R p. 251-252 double atof(const char *s) int atoi(const char *s) long atol(const char *s) double strtod(const char *s, char **endp) long strtol(const char *s, char **endp, int base) unsigned long strtoul(const char *s, char **endp, int base) CS-2303, A-Term 2012 Strings in C

Dilemma Question:– Answer:– If strings are arrays of characters, … and if arrays cannot be returned from functions, … how can we manipulate variable length strings and pass them around our programs? Answer:– Use storage allocated in The Heap! CS-2303, A-Term 2012 Strings in C

Dynamic Data Allocation 0x00000000 0xFFFFFFFF address space program code (text) global and static data heap (dynamically allocated) stack PC SP This is The Heap CS-2303, A-Term 2012 Arrays and Pointers

Typical Usage with Strings char *getTextFromSomewhere(…); int main(){ char *txt; …; txt = getTextFromSomewhere(…); printf("The text returned is %s.", txt); free(txt); } getTextFromSomewhere() cannot return pointer to automatic string variable within its own scope! Why not? CS-2303, A-Term 2012 Strings in C

Typical Usage (continued) char *getTextFromSomewhere (…) { char *t; ... t = malloc(stringLength); ... /* fill in string t*/ return t; } int main(){ char * txt; …; txt = getTextFromSomewhere (…); printf("The text returned is %s.", txt); free(txt); } Don’t forget to free() the returned string! CS-2303, A-Term 2012 Strings in C

Questions? CS-2303, A-Term 2012 Strings in C

String Manipulation in C Almost all C programs that manipulate text do so with malloc’ed and free’d memory No limit on size of string in C You need to be aware of sizes of character arrays! You need to remember to free storage when it is no longer needed Before forgetting pointer to that storage! CS-2303, A-Term 2012 Strings in C

Input-Output Functions printf(const char *format, ...) Format string may contain %s – inserts a string argument (i.e., char *) up to trailing '\0' scanf(const char *format, ...) Format string may contain %s – scans a string into argument (i.e., char *) up to next “white space” Adds '\0' Related functions fprintf(), fscanf() – to/from a file sprintf(), sscanf() – to/from a string CS-2303, A-Term 2012 Strings in C

Hazard with scanf() …; scanf("%s", word); char word[20]; …; scanf("%s", word); scanf will continue to scan characters from input until a space, tab, new-line, or EOF is detected An unbounded amount of input May overflow allocated character array Probable corruption of data! scanf adds trailing '\0' Solution:– scanf("%19s", word); CS-2303, A-Term 2012 Strings in C

Questions? CS-2303, A-Term 2012 Strings in C

Command Line Arguments See §5.10 By convention, main takes two arguments:- int main(int argc, char *argv[]); argc is number of arguments argv[0] is string name of program itself argv[i] is argument i in string form i.e., i < argc argv[argc] contains a null pointer! Sometimes you will see (the equivalent) int main(int argc, char **argv); An array of pointers to char (i.e., strings) CS-2303, A-Term 2012 Strings in C

Example — PA #2 argv[0] – name of program Instead of prompting user for game parameters, simply take them from command line % life 100 50 1000 would play the Game of Life on a grid of 100  50 squares for 1000 generations. argv[1] – first program argument CS-2303, A-Term 2012 Strings in C

Example — PA #2 (continued) int main(int argc, char *argv[])){ int xSize, ySize, gens, j; char grid[][]; if (argc <= 1) { printf("Input parameters:- "); scanf("%d%d%d", &xSize, &ySize, &gens); } else { xSize = atoi(argv[1]); ySize = atoi(argv[2]); gens = atoi(argv[3]); } grid = calloc(xSize, sizeof (char *); for (j = 0; j < xSize; j++) grid[j] = calloc(ySize, sizeof (char)); /* rest of program using grid[i][j] */ for (j = 0; j < xSize; j++) free(grid[j]; free(grid); return 0; } // main(argc, argv) CS-2303, A-Term 2012 Strings in C

Example — PA #2 (continued) int main(int argc, char *argv[])){ int xSize, ySize, gens, j; char grid[][]; if (argc <= 1) { printf("Input parameters:- "); scanf("%d%d%d", &xSize, &ySize, &gens); } else { xSize = atoi(argv[1]); ySize = atoi(argv[2]); gens = atoi(argv[3]); } grid = calloc(xSize, sizeof (char *); for (j = 0; j < xSize; j++) grid[j] = calloc(ySize, sizeof (char)); /* rest of program using grid[i][j] */ for (j = 0; j < xSize; j++) free(grid[j]; free(grid); return 0; } // main(argc, argv) Convert argument #1 to int for xSize Convert argument #2 to int for ySize Convert argument #3 to int for gens CS-2303, A-Term 2012 Strings in C

Questions? CS-2303, A-Term 2012 Strings in C