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

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

Dec 24, 2015

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: STRINGS IN C PRESENTED BY: ER. SUMANPREET KAUR LECTURER IN CE DEPTT. GPCG ASR.

STRINGS INC

PRESENTED BY:

ER. SUMANPREET KAUR

LECTURER IN CE DEPTT.

GPCG ASR.

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

Topics Covered Are:

1. Introduction2. Declaration of strings3. Initialization of strings4. Reading strings5. Writing strings6. String handling functions7. Array of strings8. Conclusion

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

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.

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

1.1 Features of strings

1. C has no native string type, instead we use arrays of char.

2. A special character, called a “null”, marks the end.

3. This may be written as ’\0’.4. This is the only character whose ASCII

value is zero.5. 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.

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

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.

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

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.…

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

a[0] a[1] a[2] a[3] a[4] a[5]

H A N D A \0

Mem 200 201 202 203 204 205 Add.

So total 6 bytes are allocated to the string ‘a’.

cont. …

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

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.

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

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 r i s \0 \0 \0 \0 \0

Contd. …….

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

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”;

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

String InputUse %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

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

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

arrayStrings shorter than the field specification

are read normally, but C always stops after reading 10 characters

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

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 */

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

String OutputUse %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 | */

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

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);}

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

Example cont…

Enter your name(last , first):Kaur Harpreet

Nice to meet you Harpreet Kaur

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

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.

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

Printing a stringThe 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.

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

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();

}

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

Example cont…

/* Sample output */Enter a string less than 50 characters with spaces: hello world

You have entered: hello world

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

String handling functionsC provides a wide range of string functions

for performing different string tasksExamples

strlen(str) - calculate string lengthstrcpy(dst,src) - copy string at src to dststrcmp(str1,str2) - compare str1 to str2

Functions come from the utility library string.h◦#include <string.h> to use

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

Commonly used functions

Function 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

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

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

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

String copy strcpy() Strcpy() copies the contents of one string into

another string. Syntax: char *strcpy(char *dst, char *src)

ocopies the characters (including the \0) from the source string (src) to the destination string (dst)

odst should have enough space to receive entire string (if not, other data may get written over)

o if the two strings overlap (e.g., copying a string onto itself) the results are unpredictable

o return value is the destination string (dst)

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

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();

}

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

String copy strcpy() cont. ..

Output of above example: source string= rajesh target string = rajesh

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

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

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

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)

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

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

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

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)

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

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

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

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

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

String Concatenation strcat()Concatenates the source string at the end of the target string.

Syntax: strcat(string1, string 2);

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

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);

}

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

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.

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

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

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

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

}OUTPUTbefore reversing string: stringafter reversing string: gnirts

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

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);

}OUTPUTthe substring is: national airport

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

Program to convert a string to all lowercasemain(){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 Airportstring after strlwr: international airport

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

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];

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

Array of stringsSometimes useful to have an array of

string valuesEach 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.

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

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]);}

}

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

Output:

• enter three name harpreet kaur rajesh kumar jasmeet kaur

• you entered harpreet kaur rajesh kumar jasmeet kaur

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

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.

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

Thanks