Tuesday, April 26, 2016

String


Strings is a set of several consecutive characters ; each character can be represented in C language by a CHAR data type . This means that string value can be represented by an array of CHAR.


Example 1 : You can put string in too many forms like below. 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
#include <stdio.h>
#include <stdlib.h>


int main()
{
char string1[] = {'h','e','l','l','o',0};
char string2[]="hello";
char string3[]={"hello"};

printf("string1=%s\n",string1);
printf("string2=%s\n",string2);
printf("string3=%s\n",string3);



return 0;

}

Output : 





Example 2 : (Scan & Print ) Implement C code that take a name and print it by using Strings.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
#include <stdio.h>
#include <stdlib.h>


int main()
{
char name[20] ;

printf("Please Enter Your Name \n");
scanf("%s",name);

printf("Your name is %s\n",name);

return 0;

}


Output : 




Example 3 : Print Array of Strings 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
#include <stdio.h>
#include <stdlib.h>


int main()
{

    int i ;
char name[4][20] = {"ahmed","Nyang","Karim","Ronlado"} ;

for (i=0;i<4;i++){
printf(" %s\n",name[i]);
}
return 0;

}

Output 





Example 4 : Copy string to string 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
#include <stdio.h>
#include <stdlib.h>
#include<string.h>

int main()
{

char name1[20] = {"Max John"} ;
char name2[20] ;

strcpy(name2,name1);
printf("name1=%s\n",name1);
printf("name2=%s\n",name2);

return 0;
}

Output : 






Example 5 : Adding string to string 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
#include <stdio.h>
#include <stdlib.h>
#include<string.h>

int main()
{

char name1[20] = {"Max "} ;
char name2[20] = {"John"} ;

strcat(name2," ");
strcat(name2,name1);

printf("Name1=%s\n",name1);
printf("Name2=%s\n",name2);
return 0 ;
}

Output : 






Example 6 : Change String Case 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
#include <stdio.h>
#include <stdlib.h>
#include<string.h>

int main()
{

char name1[20] = {"Max "} ;
char name2[20] = {"John"} ;

strlwr(name1);
strupr(name2);

printf("Name1=%s\n",name1);
printf("Name2=%s\n",name2);
return 0 ;
}

Output :






Example 7 : Finding The Length OF String 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
#include <stdio.h>
#include <stdlib.h>
#include<string.h>

int main()
{

char name1[20] = {"Max"} ;

printf("Length of Name1 is =%d\n",strlen(name1));
return 0 ;
}

Output :






Example 8 : Converting String to Integer Value 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
#include <stdio.h>
#include <stdlib.h>
#include<string.h>

int main()
{

char a[20] ={"10Max"};
char b[20] = {"John9"};
int x , y , z;

x=atoi(a);
y=atoi(b);

z=x+y;
printf("Summation =%d\n",z);

return 0 ;
}

Output : 





Share this

0 Comment to "String "

Post a Comment