Strings

String is group of characters. String is one of type of array with null character (Array will be discussed in next tutorial). Null Character ('\0') declares the end of the string. Let's different things of Strings.

How to declare a string?

char str[]="Hello"; OR char str[5]="Hello";

The above code shows us how to declare a string which is stored in variable str of data type char. Char is used for declaring characters and also declare group of characters i.e. Strings. The string is "Hello" which has 5 characters i.e 'H', 'e', 'l', 'l' and 'o' but actually it also has one null character at the end of the string i.e '\0'. Here, 5 of str[5] is the size of the array to be define. 

NOTE : In old compilers, you need to declare the size of the array i.e. keep the size as constant and it can't be variable but in new compilers you can keep the size of an array as variable.

How to read a string?

There are three ways by which you can read the string. First, you can use the scanf function to scan the string with %s and you can also use gets() function to do the same. The third is used very rarely is not of much use. The third way to scan is using getchar(), getch() or getche() functions.

Below are the syntax examples of scanf and gets(). As told the third one is very rarely used, so not providing with the syntax of it. 

scanf("%s", str);
gets(str);

Operations on strings

You can use the built-in functions to do the below mentioned operations. For that, you need to include one header named strings.h. You can add this header files like we add stdio.h header file.

#include <strings.h>

You can do the following operations on the string:-

</a> Can compare two strings
1. strcmp() function : Compares whole with ASCII
Syntax : strcmp(str1, str2);

2. strncmp() function : Compares first n bytes of the string.
Syntax : strcmp(str1, str2, n);

</b> Can find the length of the string
Syntax : n = strlen(str);

</c> Can concat two strings (i.e joining two strings)
1. strcat() function : Join both the strings
Syntax : strcat(str1, str2);

2. strncat() function : Join first n bytes of the strings
Syntax : strncat(str1, str2, n);

</d> Can reverse a string
Syntax : strrev(str1)

</e> Can extract a substring from a string
Syntax : result = strstr(str1,str2)

</f> Can copy one string from another
Syntax : strcpy(str1,str2)

Previous
Next Post »
0 Comment