Programs to learn about string operations.
String : Strings are defined as an array of characters. The difference between a character array and a string is the string is terminated with a special character ‘\0’.
Declaration of strings:
Syntax : char str_name[size];
Example : char s[10];
Initialisation of strings :
char str[] = "hello";
char str[50]="GoEduHub"
Program:
#include <stdio.h> #include<conio.h> void main() { char s[] = "GoEduHub"; int i; for (i = 0; s[i] != '\0'; ++i); printf("Length of the string: %d", i); } |
---|
Output :
Length of the string: 8
Functions of string :
S.no | Function | Purpose |
---|
1 | strcpy(s1, s2); | Copies string s2 into string s1. |
---|
2 | strcat(s1, s2); | Concatenates string s2 onto the end of string s1. |
---|
3 | strlen(s1); | Returns the length of string s1. |
---|
4 | strcmp(s1,s2); | Returns 0 if s1 & s2 are same; less than 0 if s1<s2; greater than 0 if s1>s2. |
---|
5 | strchr(s1,ch); | Returns a pointer to first occurrence of character ch in string s1. |
---|
6 | strstr(s1, s2); | Returns a pointer to the first occurrence of string s2 in string s1. |
---|
Program :
#include<stdio.h> #include<conio.h> int main () { char str1[12] = "Goeduhub"; char str2[12] = "Technologies"; char str3[12]; int len ; char ch = 'e'; char* val; char* p; // Use of strrchr() // returns "ks" val = strrchr(str1, ch); printf("String after last %c is : %s \n", ch, val); // copy str1 into str3 strcpy(str3, str1); printf("strcpy( str3, str1) : %s\n", str3 ); // concatenates str1 and str2 strcat( str1, str2); printf("strcat( str1, str2): %s\n", str1 ); // total lenghth of str1 after concatenation len = strlen(str1); printf("strlen(str1) : %d\n", len ); //comparision of strings printf("comparision of strings : %d\n",strcmp(str1,str2)); //use of strstr() p = strstr(str1, str2); if (p) { printf("String found\n"); printf("First occurrence of string '%s' in '%s' is '%s'", str2, str1, p); } else printf("String not found\n"); return 0; } |
---|
Output :
String after last e is : eduhub
strcpy( str3, str1) : Goeduhub
strcat( str1, str2): GoeduhubTechnologies
strlen(str1) : 20
comparision of strings : -1
String found
First occurrence of string 'Technologies' in 'GoeduhubTechnolo°²b' is 'Technolo°²b'
For more RTU/BTU II Sem Computer Programming Lab Experiments CLICK HERE