24
JanStrings in C with Examples: String Functions
Strings in C
Strings in C are used to store and work with text, represented as arrays of characters ending with a null character (\0). This article simplifies strings in C by explaining their structure, basic operations, and important functions for easy understanding.
In this C tutorial, we'll explore what strings are, how they work, and what you need to know when working with them in the C language. To get a little deeper, consider our C Programming Course.
What are Strings in C?
A string is a sequence of characters. e.g. "ScholarHat". Many programming languages like Java have a data type known as a string for storing string values. In C, a string is stored as an array of characters. You have to use char data type and create an array of characters for a string. The string is terminated with a null character '\0'.
- Strings in C are arrays of characters ending with a null character (\0).
- Always ensure the array size is sufficient to include the null terminator.
- Use C functions like strlen(), strcpy(), strcat(), and strcmp() for string operations.
- String literals (e.g., "Hello") are read-only and cannot be modified.
- Use scanf() for input without spaces and fgets() for input with spaces.
Strings in C are represented using double quotes ("") or single quotes (''). Whenever an array of characters e.g. c[10] gets created, the compiler implicitly appends '\0' at the end of the string.
How to declare Strings in C
In C, declaration means telling the compiler about a variable or function by specifying its type and name so the program knows how to use it.For declaring Strings in C,we use the following method that are
1. Declaring a String as a Character Array
A string can be declared as an array of characters with a fixed size.
Syntax
char str[size]
This reserves space for 20 characters (including the null terminator).
2. Declaring a String Using String Literal
A string can be directly initialized using a string literal, which automatically adds the null terminator.
char str[] = "Hello";
This creates a string with a size equal to the number of characters in "Hello" plus the null terminator.
Initializing Strings in C
Initialization in C is the process of assigning a value to a variable at the time of its declaration. This ensures that the variable starts with a known value when it is created.
1. Using a String Literal without Specifying Size
When you initialize a string with a literal, C automatically determines the size based on the number of characters in the string, including the null terminator (\0).
Example
char str[] = "Hello"; // Size is automatically determined
2. Using a String Literal with a Defined Size
You can specify the size of the string array in advance. If the literal is shorter than the array size, the remaining positions are filled with the null character (\0).
Example
char str[20] = "Hello"; // String is assigned with size 20
3. Assigning Characters One by One with a Defined Size
In this method, each character is manually assigned to the array, and you explicitly define the array’s size to hold the characters, including the null terminator.
Example
char str[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; // Each character is assigned individually
4. Assigning Characters One by One without Defining the Size
Similar to the previous method, but the size of the array is automatically set based on the number of characters you assign, including the null terminator.
Example
char str[] = {'H', 'e', 'l', 'l', 'o', '\0'}; // Size is automatically determined
Strings in C Example
Let's understand this by a given example.
#include <stdio.h>
int main(){
char str1[10]={'S', 'c', 'h', 'o', 'l', 'a', 'r', 'H', 'a', 't', '\0'};
char str2[10]="ScholarHat";
printf("String by char array method: %s\n", str1);
printf("String by String Literal method: %s\n", str2);
return 0;
}
Here, we are printing the string, "Scholarhat
" using both the methods discussed above
Note: %s
is the format specifier to print a string in C.
Output
String by char array method: ScholarHat
String by String Literal method: ScholarHat
Read More - Top 50 Mostly Asked C Interview Questions
How to access a String in C?
As the string isarray
of characters, we can access the characters of the string with their index
number. The string index starts with 0.
Example
#include <stdio.h>
int main() {
char str[10]="ScholarHat";
printf("%c", str[5]);
return 0;
}
Output
a
%c
is a format specifier to print a single character.
How to modify a String in C?
To change any specific character in a string, refer to the index
number the same as an array
. Here you also need to use single quotes,''
.
Example
#include <stdio.h>
int main() {
char str[10]="ScholarHat";
str[4] = 'i';
printf("%s", str);
return 0;
}
Output
SchoiarHat
How to loop through a string in C?
To loop through a string, for
loop is used.
Example
#include <stdio.h>
int main() {
char str[10]="ScholarHat";
for (int i = 0; i < 10; ++i) {
printf("%c\n", str[i]);
}
return 0;
}
Output
S c h o l a r H a t
String Functions in C
In C programming language, several string functions canbe used to manipulate strings. To use them, you must include the <string.h> header file in your program. Here are some of the commonly used string functions in C:
Function | Description |
---|---|
strlen() | Returns the length of a string (excluding the null terminator). |
strcpy() | Copies a string from source to destination. |
strcat() | Concatenates (joins) two strings together. |
strcmp() | Compares two strings lexicographically and returns an integer. |
strchr() | Searches for the first occurrence of a character in a string. |
strstr() | Searches for the first occurrence of a substring in a string. |
strtok() | Splits a string into tokens based on a delimiter. |
strncpy() | Copies a specified number of characters from one string to another. |
strncat() | Concatenates a specified number of characters from one string to another. |
strspn() | Returns the length of the initial segment of a string that only contains characters from a set of characters. |
strpbrk() | Searches a string for the first occurrence of any character in another string. |
strrchr() | Searches for the last occurrence of a character in a string. |
sprintf() | Formats and stores a series of characters in a string. |
Example to demonstrate some basic string functions in C Online Compiler
#include <stdio.h>
#include <string.h>
int main() {
// Declaration and Initialization
char str1[] = "ScholarHat";
char str2[20];
char search = 'o';
// strlen - String Length
printf("Length of str1: %lu\n", strlen(str1));
// strcpy - String Copy
strcpy(str2, str1);
printf("After copying, str2: %s\n", str2);
// strcat - String Concatenation
strcat(str2, " welcomes");
printf("After concatenation, str2: %s\n", str2);
// strcmp - String Comparison
int result = strcmp(str1, str2);
if (result == 0) {
printf("str1 is equal to str2\n");
} else if (result < 0) {
printf("str1 is less than str2\n");
} else {
printf("str1 is greater than str2\n");
}
// strchr
char *found = strchr(str1, search);
// Check if the character is found
if (found != NULL) {
printf("'%c' found at position: %ld\n", search, found - str1 + 1);
} else {
printf("'%c' not found in the string.\n", search);
}
return 0;
}
Output
Length of str1: 10
After copying, str2: ScholarHat
After concatenation, str2: ScholarHat welcomes
str1 is less than str2
'o' found at position: 4
Must Read For your Interview Preparation: |
C Programs MCQ: For Beginners and Experts |
Top 50 Most Asked C Interview Questions and Answers |
Summary
Strings in C can be quite challenging for some, but with a little understanding of their components, anyone can quickly become proficient. From learning the basics of fundamental string operations such as concatenation, there’s much to explore and understand. If you want to become proficient in the concepts of C programming, consider joining our C Certification course.
Do you still have doubts about the career and technology path that you should follow? So, dear learners, to clear your doubts and help you take your next step in the technology area, ScholarHat provides you with Free Technology Courses. So don't be late and miss the chance.
Further Read Articles: |
First C program and Its Syntax |
Keywords in C: List of Keywords |
Identifiers in C: Types of Identifiers |
Take this MCQ and see how ready you are for technical interviews!
Q 1: What is the correct syntax to declare a string in C?
- (a) char str[] = "Hello";
- (b) string str = "Hello";
- (c) str = "Hello";
- (d) char str = "Hello";
Q 2: Which function is used to concatenate two strings in C?
- (a) strcat()
- (b) strjoin()
- (c) stradd()
- (d) strcatf()
Q 3: What will be the output of the following code?
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[] = "Hello";
if (strcmp(str1, str2) == 0)
printf("Equal");
else
printf("Not Equal");
return 0;
}
- (a) Equal
- (b) Not Equal
- (c) Compilation Error
- (d) Runtime Error
Q 4: How is a null character represented in C?
- (a) \n
- (b) \t
- (c) \0
- (d) NULL
Q 5: Which function is used to find the length of a string in C?
- (a) strlen()
- (b) strlength()
- (c) size()
- (d) len()
FAQs
- Yes, if declared as a character array, e.g., char str[10] = "Hello";
- No, if declared as a string literal, e.g., char *str = "Hello"; (string literals are read-only).
- strlen() returns the length of the string (number of characters before \0).
- sizeof() returns the total size of the array in bytes, including the null terminator.