Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

String Functions

Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

STRING FUNCTIONS IN C

Commonly used String functions in C


Strings in C: 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’.

Some of the most commonly used String functions are:

1. strcat: The strcat() function will append a copy of the source string to the end of
destination string. The strcat() function takes two arguments:
1) dest
2) src
It will append copy of the source string in the destination string. The terminating
character at the end of dest is replaced by the first character of src .

Return value: The strcat() function returns dest, the pointer to the destination
string.

int main()
{
char dest[50] = "This is an";
char src[50] = " example";

strcat(dest, src);
printf(“%s”,dest);
return 0;
}

Output:
This is an example

2. strrchr strrchr() is a predefined function used for string handling. C string is the
header file required for string functions.

This function Returns a pointer to the last occurrence of a character in a string.


The character whose last occurrence we want to find in passed as the second argument
to the function and the string in which we have to find the character is passed as the first
argument to the function.

Syntax

DR. POOJA KAUL 1


STRING FUNCTIONS IN C

char *strrchr(const char *str, int c)

Here, str is the string and c is the character to be located. It is passed as its int promotion,
but it is internally converted back to char.

int main()
{

// initializing variables
char st[] = "GeeksforGeeks";
char ch = 'e';
char* val;

// Use of strrchr()
// returns "ks"
val = strrchr(st, ch);

printf("String after last %c is : %s \n",


ch, val);

char ch2 = 'm';

// Use of strrchr()
// returns null
// test for null
val = strrchr(st, ch2);

printf("String after last %c is : %s ",


ch2, val);

return (0);
}

Output:
String after last e is : eks
String after last m is : (null)

3. strcmp: strcmp() is a built-in library function and is declared in <string.h> header


file. This function takes two strings as arguments and compare these two strings
lexicographically.

Syntax::

int strcmp(const char *leftStr, const char *rightStr );

In the above prototype, function srtcmp takes two strings as parameters and returns an
integer value based on the comparison of strings.

DR. POOJA KAUL 2


STRING FUNCTIONS IN C

 strcmp() compares the two strings lexicographically means it starts comparison


character by character starting from the first character until the characters in both
strings are equal or a NULL character is encountered.
 If first character in both strings are equal, then this function will check the second
character, if this is also equal then it will check the third and so on
 This process will be continued until a character in either string is NULL or the
characters are unequal.

int main()
{

char leftStr[] = "g f g";


char rightStr[] = "g f g";

// Using strcmp()
int res = strcmp(leftStr, rightStr);

if (res == 0)
printf("Strings are equal");
else
printf("Strings are unequal");

printf("\nValue returned by strcmp() is: %d", res);


return 0;
}
Output:
Strings are equal
Value returned by strcmp() is: 0

4. strcpy: strcpy() is a standard library function in C/C++ and is used to copy one
string to another. In C it is present in string.h header file and in C++ it is present in cstring
header file.

Syntax:

char* strcpy(char* dest, const char* src);

Paramters: This method accepts following paramters:

 dest: Pointer to the destination array where the content is to be copied.


 src: string which will be copied.

Return Value: After copying the source string to the destination string, the strcpy()
function returns a pointer to the destination string.

Below program explains different usages of this library function:

DR. POOJA KAUL 3


STRING FUNCTIONS IN C

int main()
{
char str1[] = "Hello Geeks!";
char str2[] = "GeeksforGeeks";
char str3[40];
char str4[40];
char str5[] = "GfG";

strcpy(str2, str1);
strcpy(str3, "Copy successful");
strcpy(str4, str5);
printf("str1: %s\nstr2: %s\nstr3: %s\nstr4: %s\n",
str1, str2, str3, str4);
return 0;
}
Output:
str1: Hello Geeks!
str2: Hello Geeks!
str3: Copy successful
str4: GfG

5. strlen: The strlen() function calculates the length of a given string.The strlen()
function is defined in string.h header file. It doesn’t count null character ‘\0’.

Syntax:

int strlen(const char *str);

Parameter:

 str: It represents the string variable whose length we have to find.

Return: This function returns the length of string passed.

Below programs illustrate the strlen() function in C:

int main()
{
char ch[] = { 'g', 'e', 'e',
'k', 's', '\0' };

printf("Length of string is: %lu",


strlen(ch));

return 0;
}
Output:
Length of string is: 5

DR. POOJA KAUL 4


STRING FUNCTIONS IN C

6. strncat: strncat() is a predefined function used for string handling. string.h is the
header file required for string functions.

This function appends not more than n characters from the string pointed to by src to the
end of the string pointed to by dest plus a terminating Null-character. The initial character
of string(src) overwrites the Null-character present at the end of string(dest). Thus, length
of the string(dest) becomes strlen(dest)+n. But, if the length of the string(src) is less than
n, only the content up to the terminating null-character is copied and length of the
string(dest) becomes strlen(src) + strlen(dest).

The behavior is undefined if

 the strings overlap.


 the dest array is not large enough to append the contents of src.

Syntax:

char *strncat(char *dest, const char *src, size_t n)

Parameters: This method accepts following paramters:

 dest: the string where we want to append.


 src: the string from which ‘n’ characters are going to append.
 n: represents maximum number of character to be appended. size_t is an
unsigned integral type.

Return Value: The strncat() function shall return the pointer to the string(dest).

int main()
{

// Take any two strings


char src[50] = "efghijkl";
char dest[50] = "abcd";

// Appends 5 character from src to dest


strncat(dest, src, 5);

// Prints the string


printf("Source string : %s\n", src);
printf("Destination string : %s", dest);

return 0;
}

Output:
DR. POOJA KAUL 5
STRING FUNCTIONS IN C

Source string : efghijkl


Destination string : abcdefghi

7. strncmp: strncmp() function lexicographically compares not more than count


characters from the two null-terminated strings and returns an integer based on the
outcome.

 This function takes two strings and a number num as arguments and compare at
most first num bytes of both the strings.
 num should be at most equal to the length of the longest string. If num is defined
greater than the string length than comparison is done till the null-character(‘\0’) of
either string.
 This function compares the two strings lexicographically. It starts comparison from
the first character of each string. If they are equal to each other, it continues and
compare the next character of each string and so on.
 This process of comparison stops until a terminating null-character of either string
is reached or num characters of both the strings matches.

Syntax :

int strncmp(const char *str1, const char *str2, size_t count);

Parameters:
str1 and str2: C string to be compared.
count: Maximum number of characters to compare.
size_t is an unsigned integral type.

Return Value:
Value Meaning
Less than zero str1 is less than str2.
Zero str1 is equal to str2.
Greater than zero str1 is greater than str2.

int main()
{
// Take any two strings
char str1[10] = "aksh";
char str2[10] = "akash";

// Compare strings using strncmp()


int result = strncmp(str1, str2, 4);

if (result == 0) {
// num is the 3rd parameter

DR. POOJA KAUL 6


STRING FUNCTIONS IN C

// of strncmp() function
printf("str1 is equal to str2 upto num characters\n");
}
else if (result > 0)
printf("str1 is greater than str2\n");
else
printf("str2 is greater than str1\n");

printf("Value returned by strncmp() is: %d",


result);

return 0;
}
Output:
str1 is greater than str2
Value returned by strncmp() is: 18

8. strncpy: The strncpy() function is similar to strcpy() function, except that at most
n bytes of src are copied. If there is no NULL character among the first n character of src,
the string placed in dest will not be NULL-terminated. If the length of src is less than n,
strncpy() writes additional NULL character to dest to ensure that a total of n character are
written.

Syntax:

char *strncpy( char *dest, const char *src, size_t n )

Parameters: This function accepts two parameters as mentioned above and described
below:

 src: The string which will be copied.


 dest: Pointer to the destination array where the content is to be copied.
 n: The first n character copied from src to dest.

Return Value: It returns a pointer to the destination string.

int main()
{
char src[] = "geeksforgeeks";

// The destination string size is 14.


char dest[14];

// copying n bytes of src into dest.


strncpy(dest, src, 14);
printf("Copied string: %s\n", dest);

return 0;

DR. POOJA KAUL 7


STRING FUNCTIONS IN C

}
Output:
Copied string: geeksforgeeks

9. strrchr: The strrchr() function in C/C++ locates the last occurrence of a character
in a string. It returns a pointer to the last occurrence in the string. The terminating null
character is considered part of the C string. Therefore, it can also be located to retrieve a
pointer to the end of a string. It is defined in cstring header file.
Syntax :
const char* strrchr( const char* str, int ch )
or
char* strrchr( char* str, int ch )

Parameter :The function takes two mandatory parameters which are described below:

 str : specifies the pointer to the null terminated string to be searched for.
 ch: specifies the character to be search for.

Return Value: The function returns a pointer to the last location of ch in string, if the ch
is found. If not found, it returns a null pointer.

Below programs illustrate the above function:

int main()
{

// initializing variables
char st[] = "GeeksforGeeks";
char ch = 'e';
char* val;

// Use of strrchr()
// returns "ks"
val = strrchr(st, ch);

printf("String after last %c is : %s \n",


ch, val);

char ch2 = 'm';

// Use of strrchr()
// returns null
// test for null
val = strrchr(st, ch2);

printf("String after last %c is : %s ",


ch2, val);

DR. POOJA KAUL 8


STRING FUNCTIONS IN C

return (0);
}
Output:
String after last e is : eks
String after last m is : (null)

DR. POOJA KAUL 9

You might also like