C Strings with Examples
C strings is a very important topic.This topic covers topics like assigning values to C string,reading C strings,passing c string to a function.
This article will teach us about strings in the C programming language. We will understand how to declare and initialize them. We will also see how strings are used in C for various I/O operations with the help of examples.
We will be covering the following sections today:
- What are Stings in C?
- How to Declare and Initialize a String in C?
- Assigning Values to a C-String
- Reading C-Strings as Input from the User
- Passing a C-String to a Function
- Commonly Used String Functions in C
What are Strings in C?
In C programming, a string, aka a C-string or a C-style string, is represented by a sequence (array) of characters terminated with the null character (\0). The ASCII value of the null character is 0. Therefore, it tells the compiler where the string ends.
Here is the syntax for a C-string:
char str[] = "String";
Here, str[] is a c-string array defined using the keyword char in C. The array holds 7 characters, as illustrated below:
The null character (\0) is automatically added at the end of the string. Hence, the array’s Length is always (n+1), where ‘n’ is the number of characters in the string.
Explore: free C++ courses
Best-suited IT & Software courses for you
Learn IT & Software with these high-rated online courses
How to Declare and Initialize a String in C?
Here’s how we declare a c-string:
char str[7];
As you can see above, we have declared a string of 7 characters. By doing this, we have allocated a chunk of memory to a string-type variable that can hold seven characters.
Now, let’s understand how to initialize a string. We can do this in numerous ways:
char s[] = "Naukri";char s[50] = "Naukri";char s[] = {'N', 'a', 'u', 'k', 'r', 'i', '\0'};char s[7] = {'N', 'a', 'u', 'k', 'r', 'i', '\0'};
Let’s take another example:
char s[4] = {'L', 'e', 'a', 'r', 'n', '\0'};
Here, we are trying to assign six characters (including the null character) to a char array of size 4. Meaning it can only take four characters. This isn’t allowed.
Assigning Values to a C-String
Remember that in C programming, arrays and strings do not support the assignment operator ‘=’ once declared. For example,
char s[50] s = {'L', 'e', 'a', 'r', 'n', '\0'};
The above code would throw an error because the array type is not assignable.
Reading C-Strings as Input from the User
Using scanf() to read a string
The C language offers a scanf() function that reads a sequence of characters until it encounters whitespace (aka a space, newline character, or a tab).
For example,
#include <stdio.h>int main(){
char name[20]; printf("Enter your name: ");
//read string scanf("%s", name);
//display string
printf(“Your name is %s.”, name);
return 0;}
Output:
In the above example, even though the user entered their full name, only their first name was stored in the string name[20] and displayed in the output. Why did this happen? Because the scanf() function only read the string until the whitespace between the first and last names.
Reading a line of text from the user.
The C language offers a function fgets() that can read an entire line of string, including the whitespaces.
For example,
#include <stdio.h>int main(){ char name[20]; printf("Enter your name: "); //read string scanf("%s", name); //display string printf("Your name is %s.", name); return 0;}
Passing a C-String to a Function
In C programming, a string is passed, similar to how an array would be passed to a function.
For example,
#include <stdio.h>void displayName(char name[]);
int main(){ char name[20]; printf("Enter your name: "); //read string fgets(name, sizeof(name), stdin); //pass string to a function displayName(name); return 0;}
void displayName(char str[]){ printf("Your name is: "); puts(str);}
Output:
Commonly Used String Functions in C
The following table illustrates the most commonly used built-in string function in C:
Function | Action |
strcpy(s1, s2); | Copies string s2 into s1. |
strcat(s1, s2); | Concatenates string s2 at the end of string s1. |
strcmp(s1, s2); | Returns 0 if s1 and s2 are the same; less than 0 if s1 < s2; greater than 0 if s1 > s2. |
strchr(s1, ch); | Returns a pointer to the first occurrence of character ch in string s1. |
strstr(s1, s2); | Returns a pointer to the first occurrence of string s2 in string s1. |
strlen(s1); | Returns the length of string s1. |
Let’s look at the following example to have a quick understanding of these functions:
#include <stdio.h>#include <string.h>
int main () {
char str1[20] = "Jane"; char str2[20] = "Doe"; char str3[20]; int len ;
// Copy str1 into str3 strcpy(str3, str1); printf("strcpy( str3, str1) : %s\n", str3 );
//Concatenates str1 and str2 strcat( str1, str2); printf("strcat( str1, str2): %s\n", str1 );
//Length of str1 after concatenation len = strlen(str1); printf("strlen(str1) : %d\n", len );
return 0;}
Output:
Endnotes
I hope this article was helpful for you in understanding the strings in the C programming language. Explore our C articles to learn more about the language and consolidate your knowledge of the fundamentals.
This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio