String operations (length, compare, copy, concatenate) without including string.h using C
1. Length of the string (strlen)
The syntax of strlen is :
strlen(string);
It calculates the length of the string and returns its length. For example:
#include
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);
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:
#include=
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);
It returns 0 if string1 is same as string2 and returns 1 if they are not same. Example:
#include
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
char source[] = "Hello";
char destination[10]; //uninitialized
strcpy(destination,source);
printf("%s",destination); //prints Hello
These are some of the functions in string.h for string operation. To use these functions you must include header file
///fundamental string operation, lenth, concatenation, compare and copy strings without string.h # include #include int find_length(char string[]) { int len = 0, i; for (i = 0; string[i] != '\0'; i++) { len++; } return len; } void join_strings(char string1[], char string2[]) { int i, len1, len2; len1 = find_length(string1); len2 = find_length(string2); for (i = len1; i
Output