0% found this document useful (0 votes)
28 views19 pages

Strings

Uploaded by

SnehaSingha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views19 pages

Strings

Uploaded by

SnehaSingha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

U N I T- 3

A R R AY
&
STRUCTURE
• Arrays

SYLLABUS
• One dimensional arrays
• Two dimensional arrays
• Multi dimensional arrays
• Strings: Declaring and Initializing
strings
• Operations on strings
• Arrays of strings
• Structures
• Nested structure
• Array of Structure
• Unions
• Typedef
• enum
STRINGS
• Unlike many other programming languages, C does not have a String type to easily create string variables.
Instead, you must use the char type and create an array of characters to make a string in C. Strings are used for
storing text/characters.
• A string is a series of characters treated as a single unit. A string may include letters, digits and various special
characters such as +, -, *, / and $.
• String literals or string constants in C are written in double quotation marks as follows:
– “1000 Main Street” (a street address)
– “(080)329-7082” (a telephone number)
– “MIT ADT University” (a city)
• Syntax:-
– char fname[4];
• The above statement declares a string called fname that can take up to 3 characters. It can be indexed just as a
regular array as well.
– fname[]={‘t’,’w’,’o’};
• Generalized syntax is:-
– char str[size];
OPERATIONS ON STRINGS
• Access Strings
char abc[] = “MIT ADT";
printf("%c", abc[0]);
// Output - H
• Modify Strings
char abc[] = " MIT ADT ";
abc[0] = 'J';
printf("%s", abc);
// Outputs – JIT ADT instead of MIT ADT
• Another Way Of Creating Strings
char abc[] = {‘M', ‘I', ‘T', 'l',' ', ‘A', ‘D', ‘T'};
printf("%s", abc);
OPERATIONS ON STRINGS
• Access Strings • Another Way Of Creating Strings
char abc[] = “MIT ADT"; char abc[] = {‘M', ‘I', ‘T',' ', ‘A', ‘D', ‘T'};
printf("%c", abc[0]); printf("%s", abc);
// Output - H • Declare a string
• Modify Strings char s[5];
char abc[] = " MIT ADT "; • Initialize strings
abc[0] = 'J'; char c[] = "abcd";
printf("%s", abc); char c[50] = "abcd";
// Outputs – JIT ADT instead of MIT ADT char c[] = {'a', 'b', 'c', 'd'};
char c[5] = {'a', 'b', 'c', 'd'};
READ STRING FROM THE USER
• If we declare a string by writing char str[100];
• The scanf() function reads the sequence of characters until it encounters whitespace (space,
newline, tab, etc.).
• The string can be read using scanf() by writing scanf(“%s”,str);
• Although the syntax of scanf() function is well known and easy to use, the main pitfall with this
function is that it terminates as soon as it finds a blank space.
• Then str can be read from the user by using three ways;
Example scanf() to read a string
– Using scanf() function #include <stdio.h>
– Using gets() function int main()
{
– Using getchar(), getch(), or getche() function repeatedly
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
Enter name: MITADT University return 0;
Your name is MITADT. }
CONTI..
• The next method of reading a string a string is • The string can also be read by calling the
by using gets() function. The string can be read getchar() repeatedly to read a sequence of
by writing single characters (unless a terminating
gets(str); character is encountered) and simultaneously
storing it in a character array as follows:
• gets() is a function that overcomes the
int i=0;
drawbacks of scanf().
char str[10],ch;
• The gets() function takes the starting address
of the string which will hold the input. The getchar(ch);
string inputted using gets() is automatically while(ch!=’\0’)
terminated with a null character. {
• Example: str[i]=ch; // store the read character in str
char str[10]; i++;

printf(“Enter a string\n”); getch(ch); // get another character

gets(str); }
str[i]=’\0’; // terminate str with null character
WRITING STRING
• The string can be displayed on screen using • It terminates the line with a newline character
three ways: (‘\n’). It returns an EOF(-1) if an error occurs and
1. Using printf() function returns a positive number on success.
2. Using puts() function • Finally the string can be written by calling the
3. Using putchar() function repeatedly putchar( ) function repeatedly to print a
sequence of single characters.
• The string can be displayed using pintf() by
writing p int i=0;
char str[10]=”PPS”;
• The next method of writing a string is by using
the puts() function. The string can be displayed while(str[i]!=’\0’)
by writing: {
– puts(str); putchar(str[i]);
– printf(“%s”,str); i++;
// print the character on the screen
CONTI..
Read a string using gets() and print it
gets() and puts()
#include<stdio.h>
#include <string.h>
int main(){
char name[50];
printf("Enter your name: "); Enter your name: MIT ADT University
Your name is: MIT ADT University
gets(name); //reads string from user
printf("Your name is: ");
puts(name); //displays string
return 0;
}
LIBRARY STRING FUNCTIONS
#include <stdio.h>
• strlen() - calculates the length of a string #include <string.h>
int main () {
• strcpy() - copies a string to another char str1[12] = "Hello";
• strcmp() - compares two strings char str2[12] = "World";
char str3[12];
• strcat() - concatenates two strings int len ;

/* copy str1 into str3 */


strcpy(str3, str1);
printf("strcpy( str3, str1) : %s\n", str3 );
strcpy( str3, str1) : Hello
/* concatenates str1 and str2 */
strcat( str1, str2): HelloWorld
strcat( str1, str2);
strlen(str1) : 10 printf("strcat( str1, str2): %s\n", str1 );

/* total lenghth of str1 after concatenation */


len = strlen(str1);
printf("strlen(str1) : %d\n", len );

return 0;
}
1. STRCPY():
• It is used to copy one string to another string. The content of the second string is copied to the content of the
first string.
• Syntax:
char strcpy(char destination, char source);
• Example:
#include <stdio.h>
#include <string.h> str1 = MIT ADT University
str2 = MIT ADT University
int main() {
char str1[20] = "MIT ADT University";
char str2[20];
// copying str1 to str2
strcpy(str2, str1);
//printf("Source String = %s\n" , str1) ;
//printf("Target String = %s\n" , str2) ;
puts(str2); // MIT ADT University
return 0;
}
1. STRCPY():
It is used to copy one string to another string. The content of the second string is copied to the content of
the first string.
Syntax:
char strcpy(char destination, char source);

#include <stdio.h> #include <stdio.h>


#include <string.h> #include <string.h>
int main() { int main() {
char str1[20] = "MIT ADT University"; char str1[20] = "MIT ADT University";
char str2[20];
char str2[20];
// copying str1 to str2
// copying str1 to str2
strcpy(str2, str1);
strcpy(str2, str1);
printf(“str1 = %s\n" , str1) ;
puts(str2); // MIT ADT University printf(“str2 = %s\n" , str2) ;
return 0; return 0;
} }
MIT ADT University str1 = MIT ADT University
str2 = MIT ADT University
2. STRLEN():
The strlen() function calculates the length of a given string.
Syntax:
char strlen (name of the string);

#include<stdio.h>
#include<string.h>
int main()
{ string= welcome length=7
string= string world length=12
char abc[]="welcome";
int len1,len2;
len1= strlen(abc);
len2= strlen("string world");
printf("string= %s length=%d\n",abc,len1);
printf("string= %s length=%d\n", "string world ",len2);
return 0;
}
3. STRCAT():
It is used to concatenate i.e, combine the content of two strings.
Syntax:
strcat(string 1, string 2);

#include<stdio.h>
#include<string.h> Source String = Dear Students
int main() Target String = Hello Dear Students
{
char source[] = "Dear Students ";
char target[30]="Hello ";
strcat(target , source);
printf("Source String = %s\n" , source) ;
printf("Target String = %s\n" , target) ;
return 0;
}
4. STRCMP():
It is used to compare the contents of the two strings. If any mismatch occurs then it results the
difference of ASCII values between the first occurrence of 2 different characters.

Syntax:
int strcmp(string 1, string 2);

Example:
char mystr_a[10] = “Hello”;
char mystr_b[10] = “Goodbye”;
– mystr_a == mystr_b; // NOT allowed! The correct way is
if (strcmp(mystr_a, mystr_b ))
printf ("Strings are NOT the same.");
else
printf( "Strings are the same.");
Here it will check the ASCII value of H and G i.e, 72 and 71 and return the difference 1.
#include<stdio.h>
#include<string.h>

int main()
{
char string1[] = "Hello World";
char string2[]= "Of Programming";
int i,j,k; 0-732
i=strcmp (string1, "Hello World");
j=strcmp (string1, string2);
k=strcmp (string1, "Hello");
printf(“%d%d%d\n” , i,j,k) ;
return 0;
}
5. STRCHR():
• This function is used to determine the existence of a character in a string.
• It is used to find a character in the string and returns the index of occurrence of the
character for the first time in the string.
Syntax:
strchr(s1,’m’);

Will locate the first appearance of the character ‘m’ in string s1.
strchr(cstr);

Example:
char mystr[] = "This is a simple string";
char pch = strchr(mystr,‘s’);

The output of pch is mystr[3]


strrchr(s1,’m’);
Will locate the last appearance of the character ‘m’ in string s1.
6. STRSTR():
• It is a two –parameter function that can be used to locate a sub-string in a string.
• It is used to return the existence of one string inside another string and it results the starting
index of the string.

Syntax:
strstr(str1, str2);
strstr(s1,s2);
strstr(s1,”ABC”)

Example:
Char mystr[]="This is a simple string";
char pch = strstr(mystr,“simple”);
here pch will point to mystr[10]
C PROGRAM TO FIND STRING LENGTH
WITHOUT STRLEN
#include <stdio.h> printf("Length of \"%s\" = %d\n", s, length);
int string_length(char []); return 0;
int main() }
{ int string_length(char s[])
char s[1000]; {
int length; int c = 0;
printf("Input a string\n"); while (s[c] != '\0')
gets(s); c++;
length = string_length(s); return c;
}

You might also like