Lecture 8 String 1. Concept of strings String and pointers

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.
1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
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.
ECE Application Programming Instructor: Dr. Michael Geiger Spring 2012 Lecture 31: PE5.
To remind us We finished the last day by introducing If statements Their structure was:::::::::
C Programming Strings. Array of characters – most common type of array in C  Let’s make them easier for use Denote the end of array using a special character.
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.
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.
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)
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.
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:
© Oxford University Press All rights reserved. CHAPTER 6 STRINGS.
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.
Strings, Pointers and Tools
Principles of Programming Chapter 8: Character & String  In this chapter, you’ll learn about;  Fundamentals of Strings and Characters  The difference.
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.
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.
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.
Principles of Programming - NI Chapter 10: Character & String : In this chapter, you’ll learn about; Fundamentals of Strings and Characters The difference.
© Oxford University Press All rights reserved. Data Structures Using C, 2e Reema Thareja.
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.
מערכים (arrays) 02 אוקטובר אוקטובר אוקטובר 1602 אוקטובר אוקטובר אוקטובר 1602 אוקטובר אוקטובר אוקטובר 16 Department.
Strings CSCI 112: Programming in C.
Course Contents KIIT UNIVERSITY Sr # Major and Detailed Coverage Area
INC 161 , CPE 100 Computer Programming
Pointers & Arrays 1-d arrays & pointers 2-d arrays & pointers.
ECE Application Programming
Strings (Continued) Chapter 13
Fundamentals of Characters and Strings
CSE 303 Concepts and Tools for Software Development
CSE 303 Lecture 14 Strings in C
Module 2 Arrays and strings – example programs.
Strings A string is a sequence of characters treated as a group
Computer Science 210 Computer Organization
Arrays in C.
Programming Languages and Paradigms
מחרוזות קרן כליף.
Computer Science 210 Computer Organization
CS111 Computer Programming
C Stuff CS 2308.
INC 161 , CPE 100 Computer Programming
CSE1320 Strings Dr. Sajib Datta
Lecture 11 Strings.
C What you Know* Objective: To introduce some of the features of C. This assumes that you are familiar with C++ or java and concentrates on the features.
EECE.2160 ECE Application Programming
Strings What is a string? It is an array of characters terminated with
Chapter 8 Character Arrays and Strings
String manipulation string.h library
EECE.2160 ECE Application Programming
Exercise Arrays.
Strings in C Array of characters is called a string.
Strings #include <stdio.h>
C Characters and Strings
EECE.2160 ECE Application Programming
Introduction to Problem Solving and Programming
Chapter 12: More on C-Strings and the string Class
Presentation transcript:

Lecture 8 String 1. Concept of strings String and pointers Array of strings String operations String library

1. Concepts of String A string is a null-terminated character array. This means that after the last character, a null character (‘\0’) is stored to signify the end of the character array. The general form of declaring a string is char str[size]; For example if we write, char str[] = “HELLO”;

Concepts of String We are declaring a character array with 5 characters namely, H, E, L, L and O. Besides, a null character (‘\0’) is stored at the end of the string. So, the internal representation of the string becomes HELLO‘\0’. Note that to store a string of length 5, we need 5 + 1 locations (1 extra for the null character). The name of the character array (or the string) is a pointer to the beginning of the string. ‘\octal_number’ or ‘\xhex_number, -- for character expression, the number has be in the char range e.g. ‘a’ , ‘\141’, ‘\x61’, 97 are equivalent for char a

Example char name[ ] = “cp264”; printf(“%s”, name); // will print cp264 name array has size 6. or char name[] = {‘c’, ‘p’, ‘2’, ‘6’, ‘4’, ‘\0’};

Example use more space for string char name[ 20 ];  //name hold a string of 19 characters. name[0] = ‘c’; // or name[0] = 99; name[1] = ‘p’; name[2] = ‘2’; name[3] = ‘6’; name[4] = ‘4’; name[5] = ‘\0’; // or name[5] = 0; printf(“%s”, name); Alternative declaration initialization char name[20] = “cp264”; char name[20] = {‘c’, ‘p’, ‘2’, ‘6’, ‘4’, ‘\0’};

2. Pointers and Strings Since string is char array, array pointers and operations apply to string char name[20] = “cp264”; char *p; p = &name[0]; printf("%c\n", *p); // what this print? printf("%c\n", *(p+3)); // what this print? printf("%s\n", p+2); // what this print?

String pointer char *p1 = "cp264"; printf("%s\n", p1); printf("%c\n", *(p1+2)); Note: if a string is declared like char *a = “cp264”; Then a can only be read. *(a+1) = ‘c’; is not allowed

Pointers and Strings #include<stdio.h> main() Now, consider the following program that prints a text. #include<stdio.h> main() { char str[] = “Oxford”; char *pstr = str; printf(“\n The string is : ”); while( *pstr != ‘\0’) { printf(“%c’, *pstr); pstr++; }

3. Arrays of Strings Suppose there are 20 students in a class and we need a string that stores names of all the 20 students. How can this be done? Here, we need a string of strings or an array of strings. Such an array of strings would store 20 individual strings. An array of strings is declared as: char names[20][30]; Here, the first index will specify how many strings are needed and the second index specifies the length of every individual string. So we allocate space for 20 names where each name can be maximum 30 characters long.

example char name[5][40] = {"Data strucure II", "C programming language", "cp264"}; printf("\n%s", name[2]); printf("\n%s", name[0]); printf("\n%s", name[1]); cp264 Data strucure II C programming language name[i] is char pointer to (i-1) th string printf("\n%c", *(name5[1]+2)); // what this print? *(name[1]+2) = ‘A’; // this is allowed

// array of char pointer, each pointer point to a string char // array of char pointer, each pointer point to a string char *name[] = {"Data strucure II", "C programming language", "cp264"}; printf("\n%s", name[2]); printf("\n%s", name[0]); printf("\n%s", name[1]); // *(name[1]+2) = ‘A’; this is not allowed

Command Line Arguments main( int argc, char *argv[] ) argc = # command line arguments argv = command line arguments, array of strings $ a.out argument1 argument2 argc = 3 argv[ 0 ] = “a.out” argv[ 1 ] = “argument1” argv[ 2 ] = “argument2”

4. String operations Copy string Read string Write string Length of a string Change case Concatenate/appending string Compare string …

String copy by pointer char a[] = “C programming language”; char c[30]; int i; // copy string for (i = 0; *(a+i) !='\0'; i++) *(c+i) = *(a+i); *(c+i) = ‘\0’; // add NULL to end //print string for (i = 0; c[i] !='\0'; i++) printf("%c", c[i]); char d[30]; char *p1, *p2; p1 = a; p2 = d; for (; *p1!='\0'; p1++,p2++) *p2 = *p1; *p2 = '\0'; // add NULL to end printf("%s\n", d);

Main(){ char a[] = “C programming language”; char b[30]; copy_string(a, b); } void copy_string(char *from, char *to){ // version 1 for (; *from!='\0'; from++,to++) *to = *from; *to = '\0'; void copy_string(char *from, char *to){ // version 2 while ((*to = * from) != ‘\0’) { to++; from++; } void copy_string(char *from, char *to){ // version 3 while ((*to++ = *from++) != ‘\0’) ;

Reading Strings If we declare a string by writing char str[100]; Then str can be read from the user by using three ways using scanf function using gets() function using getchar() function repeatedly str can be read using scanf() by writing scanf(“%s”, str); str can be read by writing gets(str); gets() takes the starting address of the string which will hold the input. The string inputted using gets() is automatically terminated with a null character.

Reading Strings str can also be read by calling the getchar() function repeatedly to read a sequence of single characters (unless a terminating character is entered) and simultaneously storing it in a character array. i=0; ch = getchar (); while(ch != '*’) { str[i] = ch; i++; ch = getchar; } str[i] = '\0';

Get string from Key board input c p 2 6 4 1 7 <enter> char name[20]; scanf(“%s”, name); name has value cp264 fgets(name, sizeof(name), stdin); name has value cp264 17  

Writing Strings Strings can be displayed on screen using three ways using printf() function using puts() function using putchar() function repeatedly str can be displayed using printf() by writing printf(“%s”, str); str can be displayed by writing puts(str);

Writing Strings str can also be written by calling the putchar() repeatedly to print a sequence of single characters i=0; while(str[i] != '\0’) { putchar(str[i]); i++; }

Finding Length of a String The number of characters in a string constitutes the length of the string. For example, LENGTH(“C PROGRAMMING IS FUN”) will return 20. Note that even blank spaces are counted as characters in the string. ALGORITHM TO CALCULATE THE LENGTH OF A STRING Step 1: [INITIALIZE] SET I = 0 Step 2: Repeat Step 3 while STR[I] != NULL Step 3: SET I = I + 1 [END OF LOOP] Step 4: SET LENGTH = I Step 5: END

Converting Characters of a String into Upper Case ALGORITHM TO CONVERT THE CHARACTERS OF STRING INTO UPPER CASE Step1: [Initialize] SET I=0 Step 2: Repeat Step 3 while STR[I] != NULL Step 3: IF STR[1] >= ‘a’ AND STR[I] <= ‘z’ SET Upperstr[I] = STR[I] - 32 ELSE SET Upperstr[I] = STR[I] [END OF IF] [END OF LOOP] Step 4: SET Upperstr[I] = NULL Step 5: EXIT

4. String library #include <string.h> String copy function char *strcpy( char *destination, char *source ); e.g. char name[20]; strcpy( name, “cp264 data structures” ); 2. String length function int strlen( const char *str ); /* returns string length */ printf(“%d”, sizeof(name)); // what value ? printf(“%d”, strlen(name)); // what value ?

const char src[50] = " cp264 data structures "; char dest[50]; 3. Memory copy function void *memcpy(void *str1, const void *str2, size_t n); // copies n characters from memory area str2 to memory area str1. e..g const char src[50] = " cp264 data structures "; char dest[50]; memcpy(dest, src, strlen(src)+1);

4. String library #include <string.h> char *strcpy( char *destination, char *source ); e.g. char name[20]; strcpy( name, “cp264 data structures” ); const char src[50] = "memory copy function"; char dest[50]; printf("Before memcpy dest = %s\n", dest); memcpy(dest, src, strlen(src)+1); Get string lenghth int strlen( const char *str ); /* returns string length */ printf(“%d”, sizeof(name)); // what value ? printf(“%d”, strlen(name)); // what value ?

Concatenate two strings char *strcat( char *destination, char *source ); Source is appended to destination char s1[20] = “hello “; char s2[20] = “world.”; strcat(s1, s2); // s1 has value hello world. Compare two strings int strcmp( const char *first, const char *second ); /* ASCII order */ value = 0 if two strings are identical value = -1 if first is less than second value = 1 if first is greater than second char s1[20] = “hello “; char s2[20] = “world.”; printf(“%d”, strcmp(s1, s2)); // what’s the output?