String in C Programming: Concepts, Examples, and How to Get Started

Written by Coursera Staff • Updated on

Learn how to use a string in C programming by exploring how to create one using the char data type, ways you can use strings, and how to get started in C programming.

[Featured Image]: A man works on a laptop exploring string in C programming.

Key takeaways

C programming does not have a string data type, so you must represent characters differently than in other languages. 

  • In C programming, you use the char data type to represent a string as an array of characters. 

  • Once you create a string, you can index it, loop through it, or modify it with the string.h library.

  • You can start programming in C by working in an integrated development environment (IDE) and by using or downloading the proper C compiler for your operating system

Explore what a string in C programming is, how it differs from other languages, some common functions to use, and how you can get started with strings in C programming. If you’re ready to start building in-demand skills in software development, try the IBM Back-End Development Professional Certificate. In just six months, you’ll have the opportunity to learn about the role of back-end developers, the use of applications as microservices, and the software development lifecycle. 

What is a string in C programming?

A string in C programming is an array of characters written using the char data type. Unlike Java or C++, C does not have a string variable. So, a string in C programming is better defined as a character sequence determined by the null character '\0'. 

How does the char data type represent strings in C?

The char data type allows you to represent one of the 256 characters computers recognize using the ASCII chart. Note that at the end of every string in C is always the sentinel character '\0', which is a null value that indicates the end of the string. You can represent a single character by surrounding it in single quotations:

'C','\0'

However, to create a string of characters, such as a word, you need to represent that using double quotes:

"Coursera" 

This is the basic way of representing characters using the char data type. Explore more about how to create and initialize strings. 

Why are strings important in programming?

In programming languages, you use a string to store letters, numbers, spaces, and symbols. By storing the string, you can manipulate it as part of the software program. For example, you can use functions to find the length of a string, capitalize letters, sort characters, or replace parts of one string with another. 

How do you create a string in C?

To create a string and pass it through a variable, you can use one of two methods:

  • Representing each string individually with an array

  • Using a string literal to represent the entire string at once

The example above began to show the difference. 

Manually using character arrays

To build the string "coding" and store it in the variable "vr" manually in C, you would declare each character individually:

char vr[7] = {'c', 'o', 'd', 'i', 'n', 'g', '\0'};

This variable uses seven bytes of memory since each character, including the null, is one byte. In C, this represents the long-hand way of writing a string.

Using string literals

The more common way to write a string in C is to use a string literal. This condenses the process into simply writing the word you wish to store as a variable. 

char vr[] = "coding";

Note that using the string literal requires double quotes and automatically places the null character at the end without you having to write it. 

Examples of initializing strings in code

To initialize and print a string in a C program, you use printf() with the %s format specifier, which tells C it is using a string. In a simple script, this would look as follows:

#include <stdio.h>

int main(void){

char vr[] = "coding";

printf("I love %s", vr);

}

This prints:

I love coding

How do you access and modify strings in C?

Since strings are an array in C, you can access, modify, and loop through the characters in the string. Discover how to index, update, and loop through strings. 

Indexing characters in a string

If you want to pull a specific character out of a string, you can use the %c format specification and indicate the character through its index number, with each string index starting with 0. So, if you wanted to index the "o" out of "coding," you could use the following script:

#include <stdio.h>

int main(void){

char vr[] = "coding";

printf("%c", vr[1]); //since you want the "o" and the first index is 0, you call 1 in the function

}

This returns

o

Modifying strings

Once you have your string variable, you can also update a specific character in the string. For example, say you have the string "Boursera" saved in your function, but you need to correct it in the output with the proper spelling. To do so, you could use:

#include <stdio.h>

int main(void){

char name[] = "Boursera";

name[0] = 'C';

printf("%s", name); 

}

This returns the correct spelling:

Coursera

Using loops to iterate through strings

You can use a loop to iterate through a string, confirming each character as it goes along. Using an example above, say you need to ensure the string "Coursera" is spelled correctly, and you want to iterate through each character. To do so, you could run:

#include <stdio.h>

int main() {

  char name[] = "Coursera";

  int i;  

  for (i = 0; i < 8; ++i) {

    printf("%c\n", name[i]);

  }

  return 0;

}

This prints each letter:

C

o

u

r

s

e

r

a

How does strlen() work in C?

In C, strlen() is a function that you use to find how many characters are in a string. It is part of the string.h library in C. An example of using strlen() is as follows:

#include <stdio.h>

#include <string.h>

int main () {

char string1[] = "Hello";

printf("The length of string1 is: %d \n", strlen(string1));

}

What are the most common C string functions?

C has built-in string functions you can access with the string.h library. Some of these common functions include:

  • strncpy: Copies a specified number of letters from one string to another

  • strcat (str1, str2): Concatenates str2 to the end of str1

  • strncat ( str1, str2, n ): Concatenates the n (number of letters) from str2 onto str1

  • strlen(str1): Finds the length of the specified string

  • strcmp(str1, str2): Compares the two specified strings

How pointers work with strings

You define a pointer in C to point to a string. Recall that pointers in C allow you to represent data structures, pass values as function arguments, work with dynamically allocated memory, and effectively handle arrays. Since pointers allow you to work with memory, you could iterate through the array "Coursera" to see where each letter is stored in memory:

#include <stdio.h>

int main() {

  char name[] = "Coursera";

  int i;

  for (i = 0; i < 9; i++) {

    printf("%p\n", &name[i]);

  }

  return 0;

}

This returns the memory locations of each character. 

Real-life examples of strings in C programming

You can start using strings in C programming to handle user input, parse through text files, and even build simple text-based applications. Explore each example more below. 

Handling user input

To handle user input in C, you use the scanf() function. Using this function, you can store a string as a variable and then have the user input a particular set of data, in this case, a string. Say you want to build a program that tells a user how many letters are in their first name:

#include <stdio.h>

#include <string.h>

int main () { 

char name[30]; //creates a string and dictates how many characters it can take

printf("Please type in your first name and hit enter: \n"); //asks the user for input

scanf("%s", name); //saves the user input

printf("Your name is %zu characters long", strlen(name)); //prints the number of characters in the user's name

 return 0;

}

Building simple text-based applications by parsing text files

You can use the char and fgets() functions to open a .txt file, read it, and print the string. Say you want to build a simple text-based application that reads names from a .txt file and gives you how many characters each name has. To do so, you could:

#include <stdio.h>

#include <string.h>

int main() {

FILE *fp = fopen("your_file_path", "r");

if (!fp) {

        perror("Error opening file");

        return 1;

    }

 const unsigned MAX_LENGTH = 256;

 char buffer[MAX_LENGTH];

 while (fgets(buffer, MAX_LENGTH, fp)) {

       buffer[strcspn(buffer, "\n")] = '\0';

        printf("The name %s is %zu characters long.\n", buffer, strlen(buffer));

 }  

 fclose(fp);

  return 0;

}

How do you start programming in C?

C is a middle-level, general-purpose, procedural programming language that allows you to interact closely with a computer's hardware without writing direct machine code like binary. To start working with C programming, you need two things: 

  1. A way to write C code: You can simply produce a basic text file and label it with the ".c" extension to tag it as a C program. However, you will likely use an integrated development environment (IDE) like Visual Studio Code (VSCode) to help you write, debug, and save your files.

  2. A way to compile C code: Like Go and Swift, you need to compile C code before the machine can execute, which you can do through a C compiler. The way you compile your code varies depending on your operating system (OS). Unix (macOS) and Linux users have access to the GNU Compiler Collection (GCC), while Windows users can use Code::Blocks or use the Windows Subsystem for Linux (WSL)

Now that you're ready to start programming with C, explore some of these resources for beginners in C:

  • Resources from the official C Standards Committee

Read more: How to Become a Computer Programmer

Explore more free resources for developers and programmers

Join Career Chat on LinkedIn to get timely updates on popular skills, tools, and certifications in software development. Build or refresh your coding skills with our other free resources:

With Coursera Plus, you can learn and earn credentials at your own pace from over 350 leading companies and universities. With a monthly or annual subscription, you’ll gain access to over 10,000 programs—just check the course page to confirm your selection is included.

Updated on
Written by:

Editorial Team

Coursera’s editorial team is comprised of highly experienced professional editors, writers, and fact...

This content has been made available for informational purposes only. Learners are advised to conduct additional research to ensure that courses and other credentials pursued meet their personal, professional, and financial goals.