The Wayback Machine - https://web.archive.org/web/20240917235229/https://www.geeksforgeeks.org/strings-in-c/
Open In App

Strings in C

Last Updated : 07 Mar, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A String in C programming is a sequence of characters terminated with a null character ‘\0’. The C String is stored as an array of characters. The difference between a character array and a C string is that the string in C is terminated with a unique character ‘\0’.

string in c

C String Declaration Syntax

Declaring a string in C is as simple as declaring a one-dimensional array. Below is the basic syntax for declaring a string.

char string_name[size];

In the above syntax string_name is any name given to the string variable and size is used to define the length of the string, i.e the number of characters strings will store.

There is an extra terminating character which is the Null character (‘\0’) used to indicate the termination of a string that differs strings from normal character arrays.

C String Initialization

A string in C can be initialized in different ways. We will explain this with the help of an example. Below are the examples to declare a string with the name str and initialize it with “GeeksforGeeks”.

We can initialize a C string in 4 different ways which are as follows:

1. Assigning a String Literal without Size

String literals can be assigned without size. Here, the name of the string str acts as a pointer because it is an array.

char str[] = "GeeksforGeeks";

2. Assigning a String Literal with a Predefined Size

String literals can be assigned with a predefined size. But we should always account for one extra space which will be assigned to the null character. If we want to store a string of size n then we should always declare a string with a size equal to or greater than n+1.

char str[50] = "GeeksforGeeks";

3. Assigning Character by Character with Size

We can also assign a string character by character. But we should remember to set the end character as ‘\0’ which is a null character.

char str[14] = { 'G','e','e','k','s','f','o','r','G','e','e','k','s','\0'};

4. Assigning Character by Character without Size

We can assign character by character without size with the NULL character at the end. The size of the string is determined by the compiler automatically.

char str[] = { 'G','e','e','k','s','f','o','r','G','e','e','k','s','\0'};

Note: When a Sequence of characters enclosed in the double quotation marks is encountered by the compiler, a null character ‘\0’ is appended at the end of the string by default.

Let us now look at a sample program to get a clear understanding of declaring, and initializing a string in C, and also how to print a string with its size.

C String Example

C




// C program to illustrate strings
 
#include <stdio.h>
#include <string.h>
 
int main()
{
    // declare and initialize string
    char str[] = "Geeks";
 
    // print string
    printf("%s\n", str);
 
    int length = 0;
    length = strlen(str);
 
    // displaying the length of string
    printf("Length of string str is %d", length);
 
    return 0;
}


Output

Geeks
Length of string str is 5

We can see in the above program that strings can be printed using normal printf statements just like we print any other variable. Unlike arrays, we do not need to print a string, character by character.

Note: The C language does not provide an inbuilt data type for strings but it has an access specifier “%s” which can be used to print and read strings directly. 

Read a String Input From the User

The following example demonstrates how to take string input using scanf() function in C

C




// C program to read string from user
#include<stdio.h>
   
int main()
{  
    // declaring string
    char str[50];
       
    // reading string
    scanf("%s",str);
       
    // print string
    printf("%s",str);
   
    return 0;
}


Input

GeeksforGeeks

Output

GeeksforGeeks

You can see in the above program that the string can also be read using a single scanf statement. Also, you might be thinking that why we have not used the ‘&’ sign with the string name ‘str’ in scanf statement! To understand this you will have to recall your knowledge of scanf. 
We know that the ‘&’ sign is used to provide the address of the variable to the scanf() function to store the value read in memory. As str[] is a character array so using str without braces ‘[‘ and ‘]’ will give the base address of this string. That’s why we have not used ‘&’ in this case as we are already providing the base address of the string to scanf.

Now consider one more example,

C




// C Program to take input string which is separated by
// whitespaces
#include <stdio.h>
 
// driver code
int main()
{
 
    char str[20];
    // taking input string
    scanf("%s", str);
 
    // printing the read string
    printf("%s", str);
   
    return 0;
}


Input

Geeks for Geeks

Output

Geeks

Here, the string is read only till the whitespace is encountered.

Note: After declaration, if we want to assign some other text to the string, we have to assign it one by one or use the built-in strcpy() function because the direct assignment of the string literal to character array is only possible in declaration.

How to Read a String Separated by Whitespaces in C?

We can use multiple methods to read a string separated by spaces in C. The two of the common ones are:

  1. We can use the fgets() function to read a line of string and gets() to read characters from the standard input  (stdin) and store them as a C string until a newline character or the End-of-file (EOF) is reached.
  2. We can also scanset characters inside the scanf() function

1. Example of String Input using gets()

C




// C program to illustrate
// fgets()
#include <stdio.h>
#define MAX 50
int main()
{
    char str[MAX];
 
    // MAX Size if 50 defined
    fgets(str, MAX, stdin);
 
    printf("String is: \n");
 
    // Displaying Strings using Puts
    puts(str);
 
    return 0;
}


Input

GeeksforGeeks

Output

String is:
GeeksforGeeks

2. Example of String Input using scanset

C




// C Program to take string separated by whitespace using
// scanset characters
#include <stdio.h>
 
// driver code
int main()
{
 
    char str[20];
 
    // using scanset in scanf
    scanf("%[^\n]s", str);
 
    // printing read string
    printf("%s", str);
 
    return 0;
}


Input

Geeks for Geeks

Output

Geeks for Geeks

C String Length

The length of the string is the number of characters present in the string except for the NULL character. We can easily find the length of the string using the loop to count the characters from the start till the NULL character is found.

Passing Strings to Function

As strings are character arrays, we can pass strings to functions in the same way we pass an array to a function. Below is a sample program to do this: 

C




// C program to illustrate how to
// pass string to functions
#include <stdio.h>
 
void printStr(char str[]) { printf("String is : %s", str); }
 
int main()
{
    // declare and initialize string
    char str[] = "GeeksforGeeks";
 
    // print string by passing string
    // to a different function
    printStr(str);
 
    return 0;
}


Output:

String is : GeeksforGeeks

Note: We can’t read a string value with spaces, we can use either gets() or fgets() in the C programming language.

Strings and Pointers in C

In Arrays, the variable name points to the address of the first element.

Below is the memory representation of the string str = “Geeks”.

memory representation of strings

Similar to arrays, In C, we can create a character pointer to a string that points to the starting address of the string which is the first character of the string. The string can be accessed with the help of pointers as shown in the below example. 

C




// C program to print string using Pointers
#include <stdio.h>
 
int main()
{
 
    char str[20] = "GeeksforGeeks";
 
    // Pointer variable which stores
    // the starting address of
    // the character array str
    char* ptr = str;
 
    // While loop will run till
    // the character value is not
    // equal to null character
    while (*ptr != '\0') {
        printf("%c", *ptr);
       
        // moving pointer to the next character.
        ptr++;
    }
 
    return 0;
}


Output

GeeksforGeeks

Standard C Library – String.h  Functions

The C language comes bundled with <string.h> which contains some useful string-handling functions. Some of them are as follows:

Function Name Description
strlen(string_name) Returns the length of string name.
strcpy(s1, s2) Copies the contents of string s2 to string s1.
strcmp(str1, str2) Compares the first string with the second string. If strings are the same it returns 0.
strcat(s1, s2) Concat s1 string with s2 string and the result is stored in the first string.
strlwr() Converts string to lowercase.
strupr() Converts string to uppercase.
strstr(s1, s2) Find the first occurrence of s2 in s1.

Must Read:



Previous Article
Next Article

Similar Reads

Check if two strings are same or not without using library functions
Given two strings S1 and S2, the task is to check whether they are the same or not without using string library functions. Examples: Input: S1 = ”GeeksForGeeks”, S2 = ”GeeksForGeeks”Output: TrueExplanation:S1 and S2 are the same strings Input: S1 = ”GeeksForGeeks”, S2 = ”GeeksforGeeks”Output: False Approach: Follow the steps below to solve the prob
5 min read
Program to check if two strings are same or not
Given two strings, the task is to check if these two strings are identical(same) or not. Examples: Input: string1 = "GeeksforGeeks", string2 = "GeeksforGeeks" Output: Yes Input: string1 = "Geeks for Geeks", string2 = "Geeks for Geeks" Output: Yes Input: string1 = "GeeksforGeeks", string2 = "Geeks" Output: No Input: string1 = "Geeks for Geeks", stri
7 min read
Storage for Strings in C
In C, a string can be referred to either using a character pointer or as a character array. Strings as character arrays C/C++ Code char str[4] = &quot;GfG&quot;; /*One extra for string terminator*/ /* OR */ char str[4] = {‘G’, ‘f’, ‘G’, '&#92;&#48;'}; /* '&#92;&#48;' is string terminator */ When strings are declared as character arrays, they are st
5 min read
C function to Swap strings
Let us consider the below program. C/C++ Code #include&lt;stdio.h&gt; void swap(char *str1, char *str2) { char *temp = str1; str1 = str2; str2 = temp; } int main() { char *str1 = &quot;geeks&quot;; char *str2 = &quot;forgeeks&quot;; swap(str1, str2); printf(&quot;str1 is %s, str2 is %s&quot;, str1, str2); getchar(); return 0; } Outputstr1 is geeks,
2 min read
How to write long strings in Multi-lines C/C++?
Image a situation where we want to use or print a long long string in C or C++, how to do this? In C/C++, we can break a string at any point in the middle using two double quotes in the middle. Below is a simple example to demonstrate the same. C/C++ Code #include&lt;stdio.h&gt; int main() { // We can put two double quotes anywhere in a string char
2 min read
Why "&amp;" is not used for strings in scanf() function?
Below is syntax of Scanf. It requires two arguments: scanf("Format Specifier", Variable Address); Format Specifier: Type of value to expect while input Variable Address: &amp;variable returns the variable's memory address. In case of a string (character array), the variable itself points to the first element of the array in question. Thus, there is
2 min read
How to Concatenate Multiple Strings in C?
In C, concatenating strings means joining two or more strings end-to-end to form a new string. In this article, we will learn how to concatenate multiple strings in C. Example: Input:char str1[50] = "Hello";char str2[50] = " geeksforgeeks";Output:Hello geeksforgeeks!Concatenating Strings in CTo concatenate strings in C, we can use the strcat functi
1 min read
Array of Strings in C
In C programming String is a 1-D array of characters and is defined as an array of characters. But an array of strings in C is a two-dimensional array of character types. Each String is terminated with a null character (\0). It is an application of a 2d array. Syntax: char variable_name[r][m] = {list of string};Here, var_name is the name of the var
2 min read
C Programming Language Tutorial
In this C Tutorial, you’ll learn all C programming basic to advanced concepts like variables, arrays, pointers, strings, loops, etc. This C Programming Tutorial is designed for both beginners as well as experienced professionals, who’re looking to learn and enhance their knowledge of the C programming language. What is C?C is a general-purpose, pro
8 min read
Top 50 C Coding Interview Questions and Answers (2024)
C is the most popular programming language developed by Dennis Ritchie at the Bell Laboratories in 1972 to develop the UNIX operating systems. It is a general-purpose and procedural programming language. It is faster than the languages like Java and Python. C is the most used language in top companies such as LinkedIn, Microsoft, Opera, Meta, and N
15+ min read
Top 25 C Projects with Source Codes for 2024
If you're looking for project ideas to boost your C Programming skills, you're in the right spot. Programming is about problem-solving and adapting to ever-changing technology. Start with C, the foundation of many modern languages, to refine your programming abilities. Despite being introduced 50 years ago, C remains a top choice for beginners due
14 min read
printf in C
In C language, printf() function is used to print formatted output to the standard output stdout (which is generally the console screen). The printf function is a part of the C standard library &lt;stdio.h&gt; and it can allow formatting the output in numerous ways. Syntax of printfprintf ( "formatted_string", arguments_list);Parametersformatted_st
5 min read
Pattern Programs in C
Printing patterns using C programs has always been an interesting problem domain. We can print different patterns like star patterns, pyramid patterns, Floyd's triangle, Pascal's triangle, etc. in C language. These problems generally require the knowledge of loops and if-else statements. In this article, we will discuss the following example progra
15+ min read
C Programs
To learn anything effectively, practicing and solving problems is essential. To help you master C programming, we have compiled over 100 C programming examples across various categories, including basic C programs, Fibonacci series, strings, arrays, base conversions, pattern printing, pointers, and more. These C Examples cover a range of questions,
8 min read
Switch Statement in C
Switch case statement evaluates a given expression and based on the evaluated value(matching a certain condition), it executes the statements associated with it. Basically, it is used to perform different actions based on different conditions(cases). Switch case statements follow a selection-control mechanism and allow a value to change control of
8 min read
C Programming Interview Questions (2024)
At Bell Labs, Dennis Ritchie developed the C programming language between 1971 and 1973. C is a mid-level structured-oriented programming and general-purpose programming. It is one of the old and most popular programming languages. There are many applications in which C programming language is used, including language compilers, operating systems,
15+ min read
scanf in C
In C programming language, scanf is a function that stands for Scan Formatted String. It is used to read data from stdin (standard input stream i.e. usually keyboard) and then writes the result into the given arguments. It accepts character, string, and numeric data from the user using standard input.scanf also uses format specifiers like printf.sc
2 min read
Modulo Operator (%) in C/C++ with Examples
In C or C++, the modulo operator (also known as the modulus operator), denoted by %, is an arithmetic operator. The modulo division operator produces the remainder of an integer division which is also called the modulus of the operation. Syntax of Modulus OperatorIf x and y are integers, then the expression: x % y;pronounced as "x mod y". For examp
5 min read
C Hello World Program
The “Hello World” program is the first step towards learning any programming language and also one of the simplest programs you will learn. To print the "Hello World", we can use the printf function from the stdio.h library that prints the given string on the screen. C Program to Print "Hello World"The following C program displays "Hello World" in
2 min read
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
Since C is a structured language, it has some fixed rules for programming. One of them includes changing the size of an array. An array is a collection of items stored at contiguous memory locations.  As can be seen, the length (size) of the array above is 9. But what if there is a requirement to change this length (size)? For example,  If there is
9 min read
Format Specifiers in C
The format specifier in C is used to tell the compiler about the type of data to be printed or scanned in input and output operations. They always start with a % symbol and are used in the formatted string in functions like printf(), scanf, sprintf(), etc. The C language provides a number of format specifiers that are associated with the different
6 min read
Substring in C++
The substring function is used for handling string operations like strcat(), append(), etc. It generates a new string with its value initialized to a copy of a sub-string of this object. In C++, the header file which is required for std::substr(), string functions is &lt;string&gt;. The substring function takes two values pos and len as an argument
8 min read
Strings in C
A String in C programming is a sequence of characters terminated with a null character '\0'. The C String is stored as an array of characters. The difference between a character array and a C string is that the string in C is terminated with a unique character '\0'. C String Declaration SyntaxDeclaring a string in C is as simple as declaring a one-
8 min read
Decision Making in C (if , if..else, Nested if, if-else-if )
The conditional statements (also known as decision control structures) such as if, if else, switch, etc. are used for decision-making purposes in C programs. They are also known as Decision-Making Statements and are used to evaluate one or more conditions and make the decision whether to execute a set of statements or not. These decision-making sta
11 min read
Operators in C
In C language, operators are symbols that represent operations to be performed on one or more operands. They are the basic components of the C programming. In this article, we will learn about all the built-in operators in C with examples. What is a C Operator?An operator in C can be defined as the symbol that helps us to perform some specific math
14 min read
C Pointers
Pointers are one of the core components of the C programming language. A pointer can be used to store the memory address of other variables, functions, or even other pointers. The use of pointers allows low-level memory access, dynamic memory allocation, and many other functionality in C. In this article, we will discuss C pointers in detail, their
14 min read
Data Types in C
Each variable in C has an associated data type. It specifies the type of data that the variable can store like integer, character, floating, double, etc. Each data type requires different amounts of memory and has some specific operations which can be performed over it. The data type is a collection of data with values having fixed values, meaning
7 min read
C Arrays
Array in C is one of the most used data structures in C programming. It is a simple and fast way of storing multiple values under a single name. In this article, we will study the different aspects of array in C language such as array declaration, definition, initialization, types of arrays, array syntax, advantages and disadvantages, and many more
15+ min read
Bitwise Operators in C
In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The &amp; (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.  The | (bitwise OR) in C takes two n
7 min read
C Language Introduction
C is a procedural programming language initially developed by Dennis Ritchie in the year 1972 at Bell Laboratories of AT&amp;T Labs. It was mainly developed as a system programming language to write the UNIX operating system. The main features of the C language include: General Purpose and PortableLow-level Memory AccessFast SpeedClean SyntaxThese
6 min read
Article Tags :