Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • C
  • C Basics
  • C Data Types
  • C Operators
  • C Input and Output
  • C Control Flow
  • C Functions
  • C Arrays
  • C Strings
  • C Pointers
  • C Preprocessors
  • C File Handling
  • C Programs
  • C Cheatsheet
  • C Interview Questions
  • C MCQ
  • C++
Open In App
Next Article:
Strings in C
Next article icon

Strings in C

Last Updated : 13 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

A String in C programming is a sequence of characters terminated with a null character '\0'. The C String is work 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

Declaration

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

C
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.

Like array, we can skip the size in the above statement:

C
char array_name[]; 

Initialization

We can initialize a string either by specifying the list of characters or string literal.

C
// Using character list char str[] = {'G', 'e', 'e', 'k', 's', '\0'};  // Using string literal char str[] = "Geeks"; 

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.

Accessing

We can access any character of the string by providing the position of the character, like in array. We pass the index inside square brackets [] with the name of the string.

Example:

C
#include <stdio.h>  int main() {          char str[] = "Geeks";          // Access first character     // of string     printf("%c", str[0]);     return 0; } 

Update

Updating a character in a string is also possible. We can update any character of a string by using the index of that character.

Example:

C
#include <stdio.h>  int main() {     char str[] = "Geeks";          // Update the first     // character of string     str[0] = 'R';     printf("%c", str[0]);     return 0; } 

Output
R

String Length

To find the length of a string, you need to iterate through it until you reach the null character ('\0'). The strlen() function from the C standard library is commonly used to get the length of a string.

Example:

C
#include <stdio.h>  int main() {     char str[] = "Geeks";          printf("%d", strlen(str));     return 0; } 

Output
5

In this example, strlen() returns the length of the string "Geeks", which is 5, excluding the null character.

String Input

In C, reading a string from the user can be done using different functions, and depending on the use case, one method might be chosen over another. Below, the common methods of reading strings in C will be discussed, including how to handle whitespace, and concepts will be clarified to better understand how string input works.

Using scanf()

The simplest way to read a string in C is by using the scanf() function.

Example:

C
#include<stdio.h>    int main() {     char str[5];            // Read string     // from the user     scanf("%s",str);            // Print the string     printf("%s",str);     return 0; } 


Output

Geeks (Enter by user)
Geeks

In the above program, the string is taken as input using the scanf() function and is also printed. However, there is a limitation with the scanf() function. scanf() will stop reading input as soon as it encounters a whitespace (space, tab, or newline).

Using scanf() with a Scanset

We can also use scanf() to read strings with spaces by utilizing a scanset. A scanset in scanf() allows specifying the characters to include or exclude from the input.

Example:

C
#include <stdio.h>  int main() {     char str[20];      // Using scanset in scanf      // to read until newline     scanf("%[^\n]s", str);      // Printing the read string     printf("%s", str);      return 0; } 


Output

Geeks For Geeks (Enter by user)
Geeks For Geeks

Using fgets()

If someone wants to read a complete string, including spaces, they should use the fgets() function. Unlike scanf(), fgets() reads the entire line, including spaces, until it encounters a newline.

Example:

C
#include <stdio.h>  int main() {     char str[20];      // Reading the string      // (with spaces) using fgets     fgets(str, 20, stdin);      // Displaying the string using puts     printf("%s", str);     return 0; } 

Output

Geeks For Geeks (Enter by user)
Geeks For Geeks

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
#include <stdio.h>  void printStr(char str[]) {     printf("%s", str); }  int main() {     char str[] = "GeeksforGeeks";      // Passing string to a      // function     printStr(str);     return 0; } 

Output
GeeksforGeeks

Strings and Pointers in C

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
#include <stdio.h>  int main(){      char str[20] = "Geeks";      // 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);         ptr++;     }     return 0; } 

Output
Geeks

memory representation of strings

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:

FunctionDescription
strlen()Returns the length of string name.
strcpy()Copies the contents of string s2 to string s1.
strcmp()Compares the first string with the second string. If strings are the same it returns 0.
strcat()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()Find the first occurrence of s2 in s1.

Next Article
Strings in C

H

Harsh Agarwal
Improve
Article Tags :
  • Misc
  • C Language
  • C-String
Practice Tags :
  • Misc

Similar Reads

    C Arrays
    An array in C is a fixed-size collection of similar data items stored in contiguous memory locations. It can be used to store the collection of primitive data types such as int, char, float, etc., as well as derived and user-defined data types such as pointers, structures, etc. Creating an Array in
    7 min read
    Properties of Array in C
    An array in C is a fixed-size homogeneous collection of elements stored at a contiguous memory location. It is a derived data type in C that can store elements of different data types such as int, char, struct, etc. It is one of the most popular data types widely used by programmers to solve differe
    8 min read
    Length of Array in C
    The Length of an array in C refers to the maximum number of elements that an array can hold. It must be specified at the time of declaration. It is also known as the size of an array that is used to determine the memory required to store all of its elements.In C language, we don't have any pre-defin
    3 min read
    Multidimensional Arrays in C - 2D and 3D Arrays
    A multi-dimensional array in C can be defined as an array that has more than one dimension. Having more than one dimension means that it can grow in multiple directions. Some popular multidimensional arrays include 2D arrays which grows in two dimensions, and 3D arrays which grows in three dimension
    8 min read
    Initialization of Multidimensional Array in C
    In C, multidimensional arrays are the arrays that contain more than one dimensions. These arrays are useful when we need to store data in a table or matrix-like structure. In this article, we will learn the different methods to initialize a multidimensional array in C. The easiest method for initial
    4 min read
    Jagged Array or Array of Arrays in C with Examples
    Prerequisite: Arrays in CJagged array is array of arrays such that member arrays can be of different sizes, i.e., we can create a 2-D array but with a variable number of columns in each row. These type of arrays are also known as Jagged arrays. Example:arr[][] = { {0, 1, 2}, {6, 4}, {1, 7, 6, 8, 9},
    3 min read
    Pass Array to Functions in C
    Passing an array to a function allows the function to directly access and modify the original array. In this article, we will learn how to pass arrays to functions in C.In C, arrays are always passed to function as pointers. They cannot be passed by value because of the array decay due to which, whe
    3 min read
    How to pass a 2D array as a parameter in C?
    A 2D array is essentially an array of arrays, where each element of the main array holds another array. In this article, we will see how to pass a 2D array to a function.The simplest and most common method to pass 2D array to a function is by specifying the parameter as 2D array with row size and co
    3 min read
    How to pass an array by value in C ?
    In C programming, arrays are always passed as pointers to the function. There are no direct ways to pass the array by value. However, there is trick that allows you to simulate the passing of array by value by enclosing it inside a structure and then passing that structure by value. This will also p
    2 min read
    Variable Length Arrays (VLAs) in C
    In C, variable length arrays (VLAs) are also known as runtime-sized or variable-sized arrays. The size of such arrays is defined at run-time.Variably modified types include variable-length arrays and pointers to variable-length arrays. Variably changed types must be declared at either block scope or
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences