CSE 303 Lecture 14 Strings in C

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

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.
Ch 8. Characters and Strings Timothy Budd 2 Characters and Literals Strings Char in C++ is normally an 8-bit quantity, whereas in Java it is a 16-bit.
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.
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 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. 1 Chapter 8 - Characters and Strings Outline 8.1Introduction.
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.
CS Nov 2006 C-strings.
 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.
 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.
Programming Languages -1 (Introduction to C) strings Instructor: M.Fatih AMASYALI
Introduction to C programming
 2000 Prentice Hall, Inc. All rights reserved. Chapter 8 - Characters and Strings Outline 8.1Introduction 8.2Fundamentals of Strings and Characters 8.3Character.
February 14, 2005 Characters, Strings and the String Class.
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.
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’};
C How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
David Notkin Autumn 2009 CSE303 Lecture 17 #preprocessor Debugging is twice as hard as writing the code in the first place. Therefore, if you write the.
Characters, Strings, And The string Class Chapter 10.
Chapter 8 Strings. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-2 Strings stringC implements the string data structure using arrays of.
Strings Programming Applications. Strings in C C stores a string in a block of memory. The string is terminated by the \0 character:
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 10 Characters, Strings, and the string class.
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).
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.
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.
C Characters and Strings
Strings CSCI 112: Programming in C.
INC 161 , CPE 100 Computer Programming
Pointers & Arrays 1-d arrays & pointers 2-d arrays & pointers.
Characters and Strings
C Characters and Strings
Fundamentals of Characters and Strings
Lecture 8 String 1. Concept of strings String and pointers
Characters, C-Strings, and More About the string Class
Programming Languages -1 (Introduction to C) strings
C Programming:Part 3 Characters and Strings File Processing Exercise.
Strings A string is a sequence of characters treated as a group
Chapter 8 - Characters and Strings
Standard Version of Starting Out with C++, 4th Edition
Introduction to Programming
CS111 Computer Programming
Object Oriented Programming COP3330 / CGS5409
Characters and Strings
CprE 185: Intro to Problem Solving (using C)
Standard Version of Starting Out with C++, 4th Edition
Strings Adapted from Dr. Mary Eberlein, UT Austin.
C++ Programming Lecture 20 Strings
Strings #include <stdio.h>
Characters and Strings Functions
Strings Adapted from Dr. Mary Eberlein, UT Austin.
C Characters and Strings
Presentation transcript:

CSE 303 Lecture 14 Strings in C reading: Programming in C Ch. 9; Appendix B slides created by Marty Stepp http://www.cs.washington.edu/303/

Type char char : A primitive type representing single characters. literal char values have apostrophes: 'a' or '4' or '\n' or '\'' char letter = 'S'; printf("%c", letter); // S you can compare char values with relational operators 'a' < 'b' and 'X' == 'X' and 'Q' != 'q' An example that prints the alphabet: for (char c = 'a'; c <= 'z'; c++) { System.out.print(c); }

char and int chars are stored as integers internally (ASCII encoding) 'A' is 65, 'B' is 66, ' ' is 32, '\0' is 0 'a' is 97, 'b' is 98, '*' is 42, '\n' is 10 char letter = 'S'; printf("%d", letter); // 83 mixing char and int causes automatic conversion to int 'a' + 2 is 99, 'A' + 'A' is 130 to convert an int into the equivalent char, type-cast it (char) ('a' + 2) is 'c'

Strings in C, strings are just arrays of characters (or pointers to char) the following code works in C: char greet[7] = {'H', 'i', ' ', 'y', 'o', 'u'}; printf(greet); // output: Hi you the following versions also work and are equivalent: char greet[7] = "Hi you"; char greet[] = "Hi you"; Why does the word array have 7 elements?

Null-terminated strings in C, strings are null-terminated (end with a 0 byte, aka '\0') string literals are put into the "code" memory segment technically "hello" is a value of type const char* char greet[7] = {'H', 'i', ' ', 'y', 'o', 'u'}; char* seeya = "Goodbye"; greet seeya index 1 2 3 4 5 6 char 'H' 'i' ' ' 'y' 'o' 'u' '\0' (stack) index 1 2 3 4 5 6 7 char 'G' 'o' 'd' 'b' 'y' 'e' '\0' (heap)

String input/output other console input functions: char greet[7] = {'H', 'i', ' ', 'y', 'o', 'u'}; printf("Oh %8s!", greet); // output: Oh hi you! char buffer[80] = {'\0'}; // input scanf("%s", buffer); scanf reads one word at a time into an array (note the lack of &) if user types more than 80 chars, will go past end of buffer (!) other console input functions: gets(char*) - reads an entire line of input into the given array getchar() - reads and returns one character of input

Looping over chars don't need charAt as in Java; just use [] to access characters int i; int s_count = 0; char str[] = "Mississippi"; for (i = 0; i < 11; i++) { printf("%c\n", str[i]); if (str[i] == 's') { s_count++; } printf("%d occurrences of letter s\n", s_count);

String literals when you create a string literal with "text", really it is just a const char* (unchangeable pointer) to a string in the code area // pointer to const string literal char* str1 = "str1"; // ok str1[0] = 'X'; // not ok // stack-allocated string buffer char str2[] = "str2"; // ok str2[0] = 'X'; // ok // but pointer can be reassigned str1 = "new"; // ok str2 = "new"; // not ok main str1 str2 available heap global data code s t r 2 \0 n e w \0 s t r 1 \0

Pointer arithmetic adding/subtracting n from a pointer shifts the address by n times the size of the type being pointed to Example: Adding 1 to a char* shifts it ahead by 1 byte Example: Adding 1 to an int* shifts it ahead by 4 bytes char[] s1 = "HAL"; char* s2 = s1 + 1; // points to 'A' int a1[3] = {10, 20, 30, 40, 50}; int* a2 = a1 + 2; // points to 30 a2++; // points to 40 for (s2 = s1; *s2; s2++) { *s2++; // what does this do? }

Strings as user input char buffer[80] = {0}; scanf("%s", buffer); reads one word (not line) from console, stores into buffer problem : possibility of going over the end of the buffer fix: specify a maximum length in format string placeholder scanf("%79s", buffer); // why 79? if you want a whole line, use gets instead of scanf if you want just one character, use getchar (still waits for \n)

String library functions #include <string.h> function description int strlen(s) returns length of string s until \0 strcpy(dst, src) copies string characters from src into dst char* strdup(s) allocates and returns a copy of s strcat(s1, s2) concatenates s2 onto the end of s1 (puts \0) int strcmp(s1, s2) returns < 0 if s1 comes before s2 in ABC order; returns > 0 if s1 comes after s2 in ABC order; returns 0 if s1 and s2 are the same int strchr(s, c) returns index of first occurrence of c in s int strstr(s1, s2) returns index of first occurrence of s2 in s1 char* strtok(s, delim) breaks apart s into tokens by delimiter delim strncpy, strncat, strncmp length-limited versions of above functions

Comparing strings relational operators (==, !=, <, >, <=, >=) do not work on strings char* str1 = "hello"; char* str2 = "hello"; if (str1 == str2) { // no instead, use strcmp library function (0 result means equal) if (!strcmp(str1, str2)) { // then the strings are equal ... }

More library functions #include <ctype.h> (functions for chars) isalpha('A') returns a nonzero result (true) function description int atoi(s) converts string (ASCII) to integer double atof(s) converts string to floating-point sprintf(s, format, params) writes formatted text into s sscanf(s, format, params) reads formatted tokens from s function description int isalnum(c), isalpha, isblank, isdigit, islower, isprint, ispunct, isspace, isupper, isxdigit, tolower, toupper tests info about a single character

Copying a string 1. copying a string into a stack buffer: char* str1 = "Please copy me"; char str2[80]; // must be >= strlen(str1) + 1 strcpy(str2, str1); 2. copying a string into a heap buffer (you must free it): char* str2 = strdup(str1); 3. do it yourself (hideous, yet beautiful): char str2[80]; while (*s2++ = *s1++); // why does this work?