C Strings with Examples

C Strings with Examples

3 mins read2.2K Views Comment
Updated on Jan 19, 2023 19:12 IST

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.

2022_09_MicrosoftTeams-image-13.jpg

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 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";
Copy code

Here, str[] is a c-string array defined using the keyword char in C. The array holds 7 characters, as illustrated below:

2022_09_image-184.jpg

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.

Implementing Arrays in C Programming
Master Member Functions in C++
Exception handling in C++

Explore: free C++ courses

Recommended online courses

Best-suited IT & Software courses for you

Learn IT & Software with these high-rated online courses

18 K
1 year
39.88 K
2 years
– / –
2 years
18 K
1 year
– / –
2 years
10.8 K
6 months
16.25 K
4 weeks
19.5 K
12 months
name
ICACertificate
– / –
80 hours

How to Declare and Initialize a String in C? 

Here’s how we declare a c-string:


 
char str[7];
Copy code

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.

2022_09_image-186.jpg

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'};
Copy code

 

Let’s take another example:


 
char s[4] = {'L', 'e', 'a', 'r', 'n', '\0'};
Copy code

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'};
Copy code

The above code would throw an error because the array type is not assignable.

Classes and Objects in C++
Class Vs. Object: What are the Differences?
C Strings with Examples

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;
}
Copy code

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;
}
Copy code

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);
}
Copy code

Output:

2022_09_image-188.jpg

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;
}
Copy code

Output:

2022_09_image-189.jpg

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.

About the Author

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