Strings Programming Applications. Strings in C C stores a string in a block of memory. The string is terminated by the \0 character:

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.
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)
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.
Searching and Sorting an Array 4 Searching and sorting are two fundamental algorithms often implemented with arrays –Search an array to determine the location.
C programming---String. String Literals A string literal is a sequence of characters enclosed within double quotes: “hello world”
Chapter 10.
Chapter 8 Characters and Strings Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
CS 192 Lecture 11 Winter 2003 December 29-30, 2003 Dr. Shafay Shamail.
N-1 University of Washington Computer Programming I Lecture 19: Strings © 2000 UW CSE.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 230 Characters and Strings Literals and Variables Dale Roberts,
Computer Science 210 Computer Organization Strings in C.
 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.
Introduction to C programming
Chapter 10 Character Strings
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.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 8 - Characters and Strings Outline 8.1Introduction 8.2Fundamentals of Strings and Characters 8.3Character.
BBS514 Structured Programming (Yapısal Programlama)1 Character Processing, Strings and Pointers,
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)
 2008 Pearson Education, Inc. All rights reserved Pointers and Pointer-Based Strings.
Lecture 22: Reviews for Exam 2. Functions Arrays Pointers Strings C Files.
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’};
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI C-Style Strings Strings and String Functions Dale Roberts, Lecturer.
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.
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:
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. 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];
C++ Programming Lecture 19 Strings The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Strings, Pointers and Tools
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
Strings, and the string Class. C-Strings C-string: sequence of characters stored in adjacent memory locations and terminated by NULL character The C-string.
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.
19-Feb-02 Sudeshna Sarkar, CSE, IIT Kharagpur1 Arrays, Pointers, Strings Lecture 18 19/2/2002.
CS113 Introduction to C Instructor: Ioannis A. Vetsikas Lecture 5 : September 4.
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.
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.
Chapter 5 Pointers and Arrays Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information Engineering Da-Yeh.
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.
1 Chapter 8 – Character Arrays and Strings Outline 8.1Introduction 8.2Declaring and Initializing String 8.3Input/output of strings 8.4String-handling Functions.
Fundamentals of Characters and Strings
Characters and Strings
Command Line Arguments
C Stuff CS 2308.
Strings Adapted from Dr. Mary Eberlein, UT Austin.
Characters and Strings
Strings Adapted from Dr. Mary Eberlein, UT Austin.
Presentation transcript:

Strings Programming Applications

Strings in C C stores a string in a block of memory. The string is terminated by the \0 character:

Arrays of characters char word [] = { 'H', 'e', 'l', 'l', 'o', '!' }; To print out the contents of the array word, you run through each element in the array and display it using the %c format characters. To do processings of the word (copy, concatenate two words, etc) you need to have the actual length of the character array in a separate variable !

Strings String is an array of characters char Name[30]; char str[20] = “Initial Value”; char S[]= “Welcome”;

Example: string length // Function to count the number of characters in a string #include int stringLength (char string[]){ int count = 0; while ( string[count] != '\0' ) ++count; return count; } int main (void) { char word1[] = { 'a', 's', 't', 'e', 'r', '\0' }; char word2[] = { 'a', 't', '\0' }; char word3[] = { 'a', 'w', 'e', '\0' }; printf ("%i %i %i\n", stringLength (word1), stringLength (word2), stringLength (word3)); return 0; }

Input / Output of strings We can use %s to read and print a string printf(“Name is %s \n”, Name); scanf(“%s”, str);

Initializing character strings char word[] = "Hello!"; Is equivalent with: char word[] = { 'H', 'e', 'l', 'l', 'o', '!', '\0' }; The null string: A character string that contains no characters other than the null character char empty[]= ""; char buf[100]= ""; Initializing a very long string over several lines: char letters[] = { "abcdefghijklmnopqrstuvwxyz\ ABCDEFGHIJKLMNOPQRSTUVWXYZ" }; Adjacent strings are concatenated: char letters[] = { "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" };

String functions The C library supplies several string-handling functions; You don’t have to re-write them from scratch ! #include strcat (s1, s2) Concatenates the character string s2 to the end of s1, placing a null character at the end of the final string.The function also returns s1. strcmp (s1, s2) Compares strings s1 and s2 and returns a value less than zero if s1 is less than s2, equal to zero if s1 is equal to s2, and greater than zero if s1 is greater than s2. strcpy (s1, s2) Copies the string s2 to s1, also returning s1. strlen (s) Returns the number of characters in s, excluding the null character.

String functions (cont.) strncat (s1, s2, n) Copies s2 to the end of s1 until either the null character is reached or n characters have been copied, whichever occurs first. Returns s1. strncmp (s1, s2, n) Performs the same function as strcmp, except that at most n characters from the strings are compared. strncpy (s1, s2, n) Copies s2 to s1 until either the null character is reached or n characters have been copied, whichever occurs first. Returns s1. strchr (s, c) Searches the string s for the last occurrence of the character c. If found, a pointer to the character in s is returned; otherwise, the null pointer is returned. strstr (s1, s2) Searches the string s1 for the first occurrence of the string s2. If found, a pointer to the start of where s2 is located inside s1 is returned; otherwise, if s2 is not located inside s1, the null pointer is returned.

String Functions strcpy(s1, s2) we can not use = with string strcpy is copying s2 into s1

String Functions strlen(S) Return the length of string S strcpy(S, “industrial robot”); strlen(S) will return 16

String Functions strcmp(s1, s2) It is for comparison of s1 and s2 It return 0 if s1=s2 Return –ve if s1 is less than s2 Return +ve if s1 is greater than s2

String Functions strcat(s1, s2) It appends s2 to the end of s1

String to number conversion // Function to convert a string to an integer – my atoi #include int strToInt (const char string[]) { int i, intValue, result = 0; for ( i = 0; string[i] >= '0' && string[i] <= '9'; ++i ) { intValue = string[i] - '0'; result = result * 10 + intValue; } return result; } int main (void) { printf ("%i\n", strToInt("245")); printf ("%i\n", strToInt("100") + 25); printf ("%i\n", strToInt("13x5")); return 0; }

Example: string processing #include void concat (char result[], const char str1[], const char str2[]); int main (void) { const char s1[] = "Test " ; const char s2[] = "works." ; char s3[20]; concat (s3, s1, s2); printf ("%s\n", s3); return 0; }

Example: concatenate strings // Function to concatenate two character strings void concat (char result[], const char str1[], const char str2[]) { int i, j; // copy str1 to result for ( i = 0; str1[i] != '\0'; ++i ) result[i] = str1[i]; // copy str2 to result for ( j = 0; str2[j] != '\0'; ++j ) result[i + j] = str2[j]; // Terminate the concatenated string with a null character result [i + j] = '\0'; }

What is the output of char str1[10]; char str2[10]=“String2”; strcpy(str1, “hi bob”); if(!strcmp(str1, str2)) printf(“Equivelent \n”); strcat(str1, “x”); printf(“%s %c \n”, str1, str1[3]); strcat(str2, “have a nice day”); printf(“%s \n”, str2);

Testing strings for equality bool equalStrings (const char s1[], const char s2[]) { int i = 0; bool areEqual; while ( s1[i] == s2 [i] && s1[i] != '\0' && s2[i] != '\0' ) ++i; if ( s1[i] == '\0' && s2[i] == '\0' ) areEqual = true; else areEqual = false; return areEqual; } !!! NOT: s1==s2

Exercise Write a program to accept string and then count the vowels and reverses it. Vowels are {a, e, i, o, u, A, E, I, O, U}

Example Write a program that print the number of occurrences of a given character c in a given string s.

Trace the program int pos = 1; int count =0; char text[40]= “Welcome”; while (pos <= strlen(text)) { if(text[pos]==‘e’) {count++; printf(“+”);} pos++; } printf(“%d”, count);

Example Write a program to accept string str. Reverses string str (for example ABC > CBA). Adds (catenates) string n to the end of string str. Removes all occurrences of characters c from string str.

Example Write a function Mystrlen() to find the length of given string

Character pointers A string constant: "I am a string" is an array of characters. In the internal representation, the array is terminated with the null character '\0' so that programs can find the end. The length in storage is thus one more than the number of characters between the double quotes. a string constant is accessed by a pointer to its first element char *pmessage; pmessage = "now is the time"; assigns to pmessage a pointer to the character array. This is not a string copy; only pointers are involved !

Character pointers amessage is an array, just big enough to hold the sequence of characters and '\0' that initializes it. Individual characters within the array may be changed but amessage will always refer to the same storage. pmessage is a pointer, initialized to point to a string constant; the pointer may subsequently be modified to point elsewhere, but the result is undefined if you try to modify the string contents. char amessage[] = "now is the time"; /* an array */ char *pmessage = "now is the time"; /* a pointer */ now is the time\0 amessage pmessage

Character Pointers String constant acts like a character pointer char *pc = “ABCDE”; /* declare a character pointer variable */ Variable AddressValue constant731‘A’ constant732‘B’ constant733‘C’ constant734‘D’ constant735‘E’ constant736‘\0’ pc char s1[] = “abc”; Variable AddressValue s1[0] 900‘a’ s1[1] 901 ‘b’ s1[2] 902 ‘c’ s1[3] 903 ‘\0’ ‘A’ ‘B’ ‘C’ ‘D’ ‘E’ ‘\0’

1100 Example: char s1[] = “abc”; char *s2 = “abc”; f() { s1[1] = ‘y’; /* OK */ s2[1] = ‘y’; /* wrong (PC is OK)*/ s1 = “test”; /* wrong */ s2 = “test”; /* OK */ } Example: char s3[] = “abcdef”; f1() { char *s = s3; *s = ‘A’; /* s3[0]=‘A’ */ s = “test”; printf(“%s\n%s\n”,s,s2); } Character Pointers ‘a’ ‘b’ ‘c’ ‘\0’ CONSTANT MEMORY AREA (READ ONLY) ‘t’ ‘e’ ‘s’ ‘t’ ‘\0’ 108 s1[] ‘a’ ‘b’ ‘c’ ‘\0’ s s3[] 2000 s ‘a’ ‘b’ ‘c’ ‘d’ 2004 ‘e’ s3[0]=‘A’ ‘a’ ‘b’ ‘c’ ‘d’ 2004 ‘e’

Precedence of operators *p++ increments p after fetching the character that p points to *++p increments p before fetching the character that p points to char *p=“hello” ; printf(“%c”,*p++); // displays h char *p=“hello” ; printf(“%c”,*++p); // displays e

Character pointers and functions /* strcpy: copy t to s; array subscript version */ void strcpy(char s[], char t[]) { int i; i = 0; while ((s[i] = t[i]) != '\0') i++; } /* strcpy: copy t to s; pointer version */ void strcpy(char *s, char *t) { int i; i = 0; while ((*s = *t) != '\0') { s++; t++; }

argc and argv In environments those support C, there is a way to pass command- line arguments or parameters to a program when it begin executing. When main is called to begin execution, it is called with two arguments – argc and argv argc : The first (conventionally called argc ) is the number of command- line arguments the program was invoked with argv : The second (conventionally called argv ) is a pointer to an array of character strings that contain the arguments, one per string. Example: if echo is a program and executed on unix prompt, such as 10 echo hello world Command-Line Arguments pointer array argv argc e c h o \0 h e l l o \0 w o r l d \0 null 3

Command-Line Arguments Example: print out the arguments. ex: hello world main (int argc, char *argv[]) { int i; for (i = 1; i < argc; i++) printf(“%s%c”, argv[i], (i < argc-1) ? ‘ ’ : ‘\n’); } main (int argc, char *argv[]) { while (--argc > 0) printf(“%s%c”, *++argv, (argc > 1) ? ‘ ’ : ‘\n’); } main (int argc, char *argv[]) { while (--argc > 0) printf((argc > 1) ? “%s “ ; “%s\n“, *++argv); }

The End