2. Contents
• 3.1 Declaration and initialization, string
input/output, format specifiers
• 3.2 Standard library functions
• 3.3 Strings and pointers
• 3.4 Array of strings
• 3.5 Command Line Arguments
3. What is String?
• A string is a sequence of characters
terminated with null character ‘0’.
• In C string is defined using array of characters.
• Example char name [] = “COMPUTER”;
C O M P U T E R ‘0’
5. String input output
Input function : scanf / gets
Example
scanf(“%s”, s1);
gets(s1);
Output function: printf/puts
printf(“n s1= %s”, s1);
puts(s1);
Format Specifier
%s
6. Standard Library Functions
<string.h>
• strlen : returns length of the string
int strlen (const char *)
• strcpy : copy one string into another
void strcpy (char *, const char *)
strcpy(s1,s2);
• strcat : concantenates (combines) two strings
void strcat (char *, const char *)
strcat(s1,s2);
• strcmp : compare two strings
int strcmp (const char *, const char *)
res = strcmp (s1,s2);
7. // convert string in Upper case
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main()
{
char s[] = "computer";
printf("n string in upper case n");
for(int i; i< strlen(s);i++)
{
printf("%c",toupper(s[i]));
}
return 0;
}
8. // calculate length of the string without using std
function strlen
#include <stdio.h>
#include <string.h>
int main()
{
char s[30];
int i=0;
printf("n enter any string : ");
scanf("%s", s);
while(s[i] != '0')
i++;
printf("n length of string %s is %d",s,i);
return 0;
}
10. Use pointers to store strings and
display strings
#include <stdio.h>
#include <string.h>
int main()
{
char *name[4] = { "vinita", "vinay", "seema", "arya“ };
int i,j;
for(i=0; i<4;i++)
{ j=0;
while(*(name[i] +j) != '0')
{
printf(“%c",*(name[i] +j));
j++;
}
printf("n");
}
return 0;
}
11. Array of Strings
A string is a 1-D array of characters, so an array of strings is a 2-D array of characters.
• char names[3][6] = {
{‘A', ‘r', ‘y', ‘a’},
{'t', 'o', 'm},
{'j', 'e', 'r', 'r', 'y'}
};
• char names[3][6] = {
“Arya”,
“tom”,
“jerry”
};
0 1 2 3 4 5
0 ‘A’ ‘r’ ‘y’ ‘a’ ‘0’
1 ‘t’ ‘o’ ‘m’ ‘0’
2 ‘j’ ‘e’ ‘r’ ‘r’ ‘y’ ‘0’
12. //Array of Strings
// Display data from array of strings
#include <stdio.h>
int main()
{
char names[3][20] = { "Rutuja",
"Mansi",
"Sushmita"
};
for(int i=0;i<3;i++)
printf("%sn",names +i);
return 0;
}
13. #include <stdio.h>
#include <string.h>
int main()
{
char names[4][20];
char s[20];
int i;
printf("n enter any four names of students :");
for(i=0;i<4;i++)
{
scanf("%s",names +i);
}
printf("n The student's names aren");
for(i=0;i<4;i++)
printf("%sn",names +i);
printf("n enter the name to search in array :- ");
scanf("%s",s);
for(i=0;i<4;i++)
{
if(strcmp(s,names+i) == 0)
{
printf("n successful search...");
}
}
if(i >=4)
printf("n Unsuccessful search");
return 0;
}