Strings
String is a primitive data type which is used to store text or sequence of characters. Strings are always enclosed in double quotation marks. String is an array of characters. We will discuss arrays later on.
- char is the data type.
- name is the name of variable.
- [50] specifies the length of characters in this string variable.
Concatenation
Concatenation is a method which allows us to join two or more strings. We can use strcat() function for string concatenation.
Note: If you have numbers enclosed in quotation marks (string), they will not sum up, rather they will be concatenated.
Accessing Characters in String
As we know that strings are arrays (store multiple characters), so we can access every character using indexes inside square brackets. Arrays are data structure which can store multiple data values which have same data type.
Note: If you want to print double quotes inside string, use \"
Inputs in String
There are two methods of taking inputs in string.
Modification in Strings
We can modify our whole string or its part. We can access a specified index and can change it.
Methods of Strings
In C, there is no built-in string data type or string methods like in C++ or any other language. We represent string as array of characters in C. Whenever we want to use methods of strings, we have to include a header file #include
| Method | Description | Code |
|---|---|---|
| strlen() | It is used to calculate the length of a string variable. | printf("%d", strlen("Hi there!")); |
| strcat() | It is used to concatenate strings. | printf("%s", strcat(str1, str2)); |
| strcpy() | It is used to copy one string to the other. | strcpy(str2, str1); |
| strncpy() | It is used to copy one string to the other but allows you to specify the number of characters to copy. | char *strncpy(char *dest, const char *src, size_t n); |
| strcmp() | It is used to compare two strings. If they are same, it returns true otherwise false. | printf("%d\n", strcmp(str1, str2)); |
| *strstr() | It is used for string searching. | char *strstr(const char *haystack, const char *needle); |
Practice Exercises
Complete these exercises to reinforce your learning and earn XP