PRESENTED BY: ER. SUMANPREET KAUR LECTURER IN CE DEPTT. GPCG ASR.

Slides:



Advertisements
Similar presentations
Strings.
Advertisements

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.
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.
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 9 Strings Instructor: Alkar / Demirer. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-2 Strings stringC implements the string data.
Chapter 9 Character Strings
Chapter 10.
Topic 10 - Strings.
Introduction to Computers and Programming Class 22 Character Arrays (Strings) Professor Avi Rosenfeld.
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.
CS 201 String Debzani Deb.
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.
Computer Science 210 Computer Organization Strings in C.
Data Structure and C Part-6. Naming a Function Any valid variable-name can be given to the user-defined function. The main program itself is considered.
1. An array is a collection of a fixed number of components wherein all of the components are of the same type Example: Suppose that there is a list of.
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.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 8 - Characters and Strings Outline 8.1Introduction 8.2Fundamentals of Strings and Characters 8.3Character.
STRING Dong-Chul Kim BioMeCIS UTA 10/7/
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT8: Characters and Strings CS2311 Computer Programming.
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.
Lecturer: Omid Jafarinezhad Sharif University of Technology Department of Computer Engineering 1 Fundamental of Programming (C) Lecture 6 Array and String.
Chapter 8: Character and String CMPD144: Programming 1.
Chapter 8 Strings. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-2 Strings stringC implements the string data structure using arrays of.
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:
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
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.
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];
5.6 String Processing Part 2. Sprintf(destnvar,…..regularprintf) Write formatted data to string Same as printf except the output is put in variable. A.
UniMAP SEM I - 09/10EKT 120 Computer Programming1 Lecture 8 – Arrays (2) & Strings.
Strings, Pointers and Tools
CMSC 104, Version 8/061L25Strings.ppt Strings Topics String Libraries String Operations Sample Program Reading Sections
Characters and Strings
Principles of Programming Chapter 8: Character & String  In this chapter, you’ll learn about;  Fundamentals of Strings and Characters  The difference.
DCT1063 Programming 2 CHAPTER 3 STRINGS Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
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.
Dr. Sajib Datta Feb 21,  In the last class we discussed: ◦ Bubble sort  How it works  performance.
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.
String in C++. 2 Using Strings in C++ Programs String library or provides functions to: - manipulate strings - compare strings - search strings ASCII.
Strings CSCI 112: Programming in C.
Course Contents KIIT UNIVERSITY Sr # Major and Detailed Coverage Area
Lecture 8 String 1. Concept of strings String and pointers
Strings A string is a sequence of characters treated as a group
Arrays in C.
Lecture 11 Strings.
Strings.
Strings Dr. Soha S. Zaghloul updated by Rasha ALEidan
Chapter 2 Array and String Visit to more Learning Resources.
Strings What is a string? It is an array of characters terminated with
Strings in C Array of characters is called a string.
CS31 Discussion 1H Fall18: week 6
Introduction to Problem Solving and Programming
Presentation transcript:

PRESENTED BY: ER. SUMANPREET KAUR LECTURER IN CE DEPTT. GPCG ASR. STRINGS IN C PRESENTED BY: ER. SUMANPREET KAUR LECTURER IN CE DEPTT. GPCG ASR.

Topics Covered Are: Introduction Declaration of strings Initialization of strings Reading strings Writing strings String handling functions Array of strings Conclusion

1. Intoduction String is sequence or collection of characters terminated by null character. Null terminates the string but not part of it. Strings are accessed through arrays/ pointer . String.h contains prototypes of many useful functions.

1.1 Features of strings C has no native string type, instead we use arrays of char. A special character, called a “null”, marks the end. This may be written as ’\0’. This is the only character whose ASCII value is zero. Depending on how arrays of characters are built, we may need to add the null by hand , or the compiler may add it for us.

2. Declaration of strings The strings can be declared as array of character. The general syntax is: char name_of_string[length]; Char is data type. Name_of _string is user defined name given to string variable. [length]: defines the size of the string.

Example of declaration of strings char a[10]; in above example ‘a’ is string variable of length 10 characters. char a[]={‘H’, ’A’, ’N’, ’D’ ,’A’, ’\0’,}; In memory the character array or string is cont.…

a[0] a[1] a[2] a[3] a[4] a[5] H A N D \0 Mem 200 201 202 203 204 205 Add. So total 6 bytes are allocated to the string ‘a’. cont. …

CONTD. … Notice that even though there are only five characters in the world ‘HONDA’ , six characters are stored in computer. The last character, the character’/0’ is the NULL character, which indicates the end of string. Therefore , if any array of characters is to be used to store a string , the array must be large enough to store the string and its terminating NULL character.

3.Initialization of strings we can itialize string variables at compile time such as: char name[10]=“Arris”; This initialization creates the following spaces in storage: [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] A r i s \0 Contd. …….

Initialization of strings if we happen to declare a string like this : char my_drink[3]= “tea”; we will get the following syntax error: error c2117:’tea’: array bound overflow . instead , we need to at lest declare the array with (the size of string +1) to accommodate the null terminate character’\0’. char my_drink[4]=“tea”;

String Input Use %s field specification in scanf to read string ignores leading white space reads characters until next white space encountered C stores null (\0) char after last non-white space char Reads into array (no & before name, array is a pointer) Example: char Name[11]; scanf(“%s”,Name); Problem: no limit on number of characters read (need one for delimiter), if too many characters for array, problems may occur

String Input (cont) Can use the width value in the field specification to limit the number of characters read: char Name[11]; scanf(“%10s”,Name); Remember, you need one space for the \0 width should be one less than size of array Strings shorter than the field specification are read normally, but C always stops after reading 10 characters

String Input (cont) Edit set input %[ListofChars] Examples: ListofChars specifies set of characters (called scan set) Characters read as long as character falls in scan set Stops when first non scan set character encountered Note, does not ignored leading white space Any character may be specified except ] Putting ^ at the start to negate the set (any character BUT list is allowed) Examples: scanf(“%[-+0123456789]”,Number); scanf(“%[^\n]”,Line); /* read until newline char */

String Output Use %s field specification in printf: characters in string printed until \0 encountered char Name[10] = “Rich”; printf(“|%s|”,Name); /* outputs |Rich| */ Can use width value to print string in space: printf(“|%10s|”,Name); /* outputs | Rich| */ Use - flag to left justify: printf(“|%-10s|”,Name); /* outputs |Rich | */

Input/Output Example #include <stdio.h> void main() { char LastName[11]; char FirstName[11]; printf("Enter your name (last , first): "); scanf("%10s%*[^,],%10s",LastName,FirstName); printf("Nice to meet you %s %s\n", FirstName,LastName); }

Example cont… Enter your name(last , first): Kaur Harpreet Nice to meet you Harpreet Kaur

Readind a string The drawback of reading a string using scanf() is that it does not read whitespaces or whole line If the string to be read as an input has embedded whitespace characters, use standard gets() function.

Printing a string The drawback of printing a string using printf() is that it does not print whitespaces. If the string to be print as an output has embedded whitespace characters, use standard puts() function.

Example of gets()/puts() #include <stdio.h> void main(void) { char string1[50]; char string2[50]; printf("Enter a string less than 50 characters with spaces: \n "); gets(string1); printf("\nYou have entered: "); puts(string1); getch(); }

Example cont… /* Sample output */ Enter a string less than 50 characters with spaces: hello world You have entered: hello world

String handling functions C provides a wide range of string functions for performing different string tasks Examples strlen(str) - calculate string length strcpy(dst,src) - copy string at src to dst strcmp(str1,str2) - compare str1 to str2 Functions come from the utility library string.h #include <string.h> to use

Commonly used functions Description Strlen() To calculate the length of string. Strcpy() To copy the contents of one string to another Strcat() To concatenate the two strings Strcmp() To compare two strings Strstr() To find the first occurrence of a substring in another string Strrev() Reverse string Strlwr() Converts a string to lowercase Strupr() Converts the string to uppercase Strset() Sets all characters of string to a given number

String Length strln() strln() counts the number of characters in a string. Syntax: int strlen(char *str) returns the length (integer) of the string argument counts the number of characters until an \0 encountered does not count \0 char Example: char str1 = “hello”; strlen(str1) would return 5

String copy strcpy() Strcpy() copies the contents of one string into another string. Syntax: char *strcpy(char *dst, char *src) copies the characters (including the \0) from the source string (src) to the destination string (dst) dst should have enough space to receive entire string (if not, other data may get written over) if the two strings overlap (e.g., copying a string onto itself) the results are unpredictable return value is the destination string (dst)

String copy strcpy() cont. .. Example: #include<stdio.h> #include<conio.h> Void main() { char source[]=“rajaesh”; char target[20]; strcpy(target,source); printf(“source string=%s\n”,source); printf(“target string=%s\n”,target); getch(); }

String copy strcpy() cont. .. Output of above example: source string= rajesh target string = rajesh

Example: strcpy #include <stdio.h> #include <string.h> void main(void) { char string1[100] = "Malaysia"; char string2[50] = "Gemilang"; strncpy(string1, string2, 4); printf(“string1: %s\n", string1); } Output: string1: Gemiysia

String comparison strcmp() Syntax: int strcmp(char *str1, char *str2) compares str1 to str2, returns a value based on the first character they differ at: less than 0 if ASCII value of the character they differ at is smaller for str1 or if str1 starts the same as str2 (and str2 is longer)

String comparison strcmp() greater than 0 if ASCII value of the character they differ at is larger for str1 or if str2 starts the same as str1 (and str1 is longer) 0 if the two strings do not differ

String Comparison (cont) strcmp examples: strcmp(“hello”,”hello”) -- returns 0 strcmp(“yello”,”hello”) -- returns value > 0 strcmp(“Hello”,”hello”) -- returns value < 0 strcmp(“hello”,”hello there”) -- returns value < 0 strcmp(“some diff”,”some dift”) -- returns value < 0 expression for determining if two strings s1,s2 hold the same string value: !strcmp(s1,s2)

String Comparison (cont) Sometimes we only want to compare first n chars: int strncmp(char *s1, char *s2, int n) Works the same as strcmp except that it stops at the nth character looks at less than n characters if either string is shorter than n strcmp(“some diff”,”some DIFF”) -- returns value > 0 strncmp(“some diff”,”some DIFF”,4) -- returns 0

String Comparison (ignoring case) Syntax: int strcasecmp(char *str1, char *str2) similar to strcmp except that upper and lower case characters (e.g., ‘a’ and ‘A’) are considered to be equal int strncasecmp(char *str1, char *str2, int n) version of strncmp that ignores case

String Concatenation strcat() Concatenates the source string at the end of the target string. Syntax: strcat(string1, string 2);

Example: strcat /* Concatenating Strings Using strcat */ #include <stdio.h> #include <string.h> void main() { char str1[50] = "Hello "; char str2[ ] = "World"; strcat(str1, str2); printf("str1: %s\n", str1); }

Example: strcat cont. … Output: str1: Hello World Note : This only works if you've defined the str1 array to be large enough to hold the characters of your string. If you don't specify a size, the program may crash.

Example: strncat /* Concatenating Strings Using strncat */ #include <stdio.h> #include <string.h> void main() { char str1[50] = "Hello "; char str2[ ] = "World"; strncat(str1, str2, 2); printf("str1: %s\n", str1); } Output: str1: Hello Wo

Program to reverses all characters in a string main() { char *str=“string”; printf(“before reversing string: %s\n”, str); strrev(str); printf(“after reversing string: %s\n”, str); } OUTPUT before reversing string: string after reversing string: gnirts

Program to find the first occurrence of a substring in another string main() { char*str1=“International airport:”,*str2=“nation”,*ptr; ptr= strstr(str1,str2); printf(“the substring is: %\n”,ptr); } OUTPUT the substring is: national airport

Program to convert a string to all lowercase main() { char *str=“International Airport”; printf(“string prior to strlwr: %s\n”, str); strlwr(str); printf(“string after strlwr: %s\n”, str); } OUTPUT: string prior to strlwr:International Airport string after strlwr: international airport

Array of strings Arrays of strings can be declared and handled in a similar manner to that described for 2-D Dimensional arrays. Syntax: <data type><name of string>[number of strings] [number of characters];

Array of strings Sometimes useful to have an array of string values Each string could be of different length (producing a ragged string array) Example: char *MonthNames[13]; /* an array of 13 strings */ MonthNames[1] = “January”; /* String with 8 chars */ MonthNames[2] = “February”; /* String with 9 chars */ MonthNames[3] = “March”; /* String with 6 chars */ etc.

Exanple of array of strings #include<stdio.h> #include<conio.h> main() { char name[3][10]; int i; clrscr(); printf(“\n enter three name”); for(i=0; i<3; i++) scanf(“%s”,name[i]); printf(“\n you entered”); } printf(“\n %s”,name[i]);

Output: enter three name harpreet kaur rajesh kumar jasmeet kaur you entered

Conclusion Today we have learn about: what are strings? How we declare them? What are different methods for reading and writing strings? Various function that are performed on strings. How strings are stored in array.

Thanks