In C, string.h includes various build in functions for string operations. The main operations are
1. Length of the string (strlen)
The syntax of strlen is :
It calculates the length of the string and returns its length. For example:
The above code displays 5, because Mumbai consists of 5 characters. Note: it does not count null character.
2. Joining two strings (strcat)
The syntax of strcat is
Now it removes the null character from string1 and joins the first character of string2 at that position. Now string1 consists of both string1 and string2 in joined form. Example:
3. Comparing two strings(strcmp)
The syntax of strcmp is
It returns 0 if string1 is same as string2 and returns 1 if they are not same. Example:
4. Copying one string to another (strcpy)
The syntax of strcpy is
It copies the content of source_string to destination_string. Example:
These are some of the functions in string.h for string operation. To use these functions you must include header file <string.h>. But we can make our own functions to perform above task without including string,h. Here is the complete source code that has own functions find_length (like strlen) to find length, join_strings( like strcat) for joining strings, compare_strings(like strcmp) for comparing two strings and copy_string(like strcpy) to copy one string from another. Observer carefully the code, if you are beginner, you will learn a lot of things about string operation.
Source Code
Read more »
1. Length of the string (strlen)
The syntax of strlen is :
strlen(string);
#include<string.h>
string = "Mumbai";
printf("Length = %d",strlen(string));
The above code displays 5, because Mumbai consists of 5 characters. Note: it does not count null character.
2. Joining two strings (strcat)
The syntax of strcat is
strcat(string1,string2);
#include<string.h>
char string1[] = "Anti";
char string2[] = "Particle";
strcat(string1,string2);
printf("%s",string1); //display AntiParticle
3. Comparing two strings(strcmp)
The syntax of strcmp is
strcmp(string1,string2);#include<string.h>
char string1 = "Nepal";
char string2 = "Srilanka";
if(strcmp(string1,string2)==0){
printf("They are equal");
}else{printf("They are not equal"); //this is executed
}
4. Copying one string to another (strcpy)
The syntax of strcpy is
strcpy(destination_string, source_string);It copies the content of source_string to destination_string. Example:
#include<string.h>
char source[] = "Hello";
char destination[10]; //uninitialized
strcpy(destination,source);printf("%s",destination); //prints Hello
Source Code
تعليقات: 0
إرسال تعليق