5.89k likes | 12.95k Views
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
E N D
STRINGS INC 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] 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] 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] • 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
String Length strln() • strln() counts the number of characters in a string. • Syntax: int strlen(char *str) returns thelength (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”,”somedift”) -- 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:InternationalAirport 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”); } for(i=0; i<3; i++) { printf(“\n %s”,name[i]); } }
Output: • enter three name harpreetkaur rajeshkumar jasmeetkaur • you entered harpreetkaur rajeshkumar jasmeetkaur
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.