DS Unit1 Strings
DS Unit1 Strings
String Initialization
char str[]=“Hello”;
char str[5]=“hello”;
char str[]={‘h’, ’e’ , ’l’ , ’l’ , ’o’ , ’\0’};
To store a string of length n , we need n+1 location(1 extra for null)
Reading String
Using scanf() Using getchar()
#include<stdio.h>
void main()
{char s1[10];
printf("enter a string \n");
scanf("%s",s1); // New
printf("\ns1=%s",s1); // New
}
using gets()
Inserting a string in main string
INSERT("XYZXYZ", 3, "AAA") = "XYZAAAXYZ"
Text: Welcome
Str: come
Max:7-4+1=4
Inbuilt string function (string.h)
function Action Syntax
strcat() Concatenates two strings strcat(str1,str2)
strcmp() Compares two strings strcmp(str1,str2)
Return 0 if equal else numeric
difference of between the first
non matching
strcpy() Copies one string to another strcpy(str1,str2)
strlen() Find length of string N=strlen(str1)
strncpy() Copies leftmost n characters of strncpy(str1,str2,n)
one string to another
strncmp() Compares leftmost n characters strncmp(str1,str2,n)
of two strings
strncat() Concatenates leftmost n strncat(str1,str2,n)
characters of string str2
strstr() Used to locate substring in strstr(str1,str2)
astring
strcat()
#include<stdio.h>
#include<string.h>
void main()
{char s1[20],s2[10];
gets(s1);
gets(s2);
puts(strcat(s1,s2));
}
strcmp()
#include<stdio.h>
#include<string.h>
void main()
{char s1[20],s2[10],s3[10];
int a,b;
gets(s1);
gets(s2);
gets(s3);
a=strcmp(s1,s2);
printf("a=%d\n",a);
b=strcmp(s1,s3);
printf("b=%d",b);
}
String Concatenate
#include <stdio.h>
int main() {
char str1[20],str2[20],str3[40];
int i,j;
printf("enter the string1");
gets(str1);
printf("enter the string2");
gets(str2);
printf("string 1= %s string 2%s\n",str1,str2);
for(i=0;str1[i]!='\0';i++)
str3[i]=str1[i];
str3[i]=' ';
i=i+1;
for(j=0;str2[j]!='\0';j++)
str3[i+j]=str2[j];
printf("string3%s\n",str3);
return 0;
}
String Compare
#include <stdio.h>
int main() {
char str1[20],str2[20];
int i=0;
printf("enter the string1");
gets(str1);
printf("enter the string2");
gets(str2);
printf("string 1= %s string 2%s\n",str1,str2);
while((str1[i]==str2[i])&&(str1[i]!='\0')&&(str2[i]!='\0'))
i=i+1;
if(str1[i]=='\0'&&str2[i]=='\0')
printf("strings are equal");
else
printf("strings are not equal");
return 0;
}
String Copy and string length
#include <stdio.h>
int main() {
char str1[20],str2[20];
int i;
printf("enter the string1");
gets(str1);
printf("string 1 %s\n",str1);
for(i=0;str1[i]!='\0';i++)
str2[i]=str1[i];
str2[i]='\0';
printf("string2%s\nthe number of characters in a string=%d",str2,i);
}
Pointers and Strings
#include <stdio.h>
int main() {
char *name, *p;
name= "New";
p=name;
puts(name);
while(*p!='\0')
{
printf("%c is stored at address %u\n",*p, p);
p++;
}
return 0;
}
Array of pointers
Char name[3][25]; declare 75 bytes
#include <stdio.h>
int main() {
char *name[3]={"New","Newyork","New
Zealand"};
puts(name[0]);
puts(name[1]);
puts(name[2]);
return 0;
}
char *name[3] uses 24 bytes
END