Strings in C

In this tutorial, we will learn about strings in C. A string is a group of characters that ends with a special character called \0. C stores strings in arrays of characters. We will also see how to use functions like strlen, strcpy, and strcmp to work with strings.

Contents:

  1. What are Strings in C?
  2. Declaring and Initializing Strings in C
  3. Input and Output of Strings in C
  4. Using printf() and scanf() in C
  5. Using gets() and puts() in C
  6. fgets() in C
  7. String Manipulation Functions in C
  8. Finding String Length (strlen()) in C
  9. Copying Strings (strcpy()) in C
  10. Concatenating Strings (strcat()) in C
  11. Searching for a Character (strchr()) in C
  12. Finding a Substring (strstr()) in C
  13. Reversing a String (strrev()) in C
  14. Differences Between Strings and Character Arrays in C
  15. FAQs on Strings in C

What are Strings in C?

A string in C is a sequence of characters stored in an array and ended with a null character (\0). Unlike other languages, C does not have a built-in string type. Instead, it uses character arrays (char[]) or pointers (char*) to work with strings.

Declaring and Initializing Strings in C

There are multiple ways to declare and initialize strings in C:

1. Using Character Array (With Explicit Size)

advertisement
char name[10] = "Sanfoundry";

Stores the string “Sanfoundry” with an extra \0 at the end. Size must be large enough to store the string and null character.

2. Using Character Array (Without Explicit Size)

char name[] = "Sanfoundry";

The compiler automatically determines the size (10 characters, including \0).

Free 30-Day C++ Certification Bootcamp is Live. Join Now!

3. Using Individual Characters

char name[] = {'S', 'a', 'n', 'f', 'o', 'u', 'n', 'd', 'r', 'y', '\0'};

Requires \0 explicitly at the end to indicate the end of the string.

4. Using a Pointer

char *name = "Sanfoundry";

It points to a string stored in read-only memory. Changing it can cause errors.

Example: Declaring and Initializing Strings

#include <stdio.h>
 
int main()
{
    char quiz1[] = "C Programming";
    char quiz2[15] = "Sanfoundry";
    char *quiz3 = "String in C";
 
    printf("Quiz 1: %s\n", quiz1);
    printf("Quiz 2: %s\n", quiz2);
    printf("Quiz 3: %s\n", quiz3);
 
    return 0;
}

Output:

advertisement
Quiz 1: C Programming
Quiz 2: Sanfoundry
Quiz 3: String in C

This C program shows three ways to store and print strings.

  • quiz1 is a character array that holds the string “C Programming”. The size of the array is set automatically by the compiler.
  • quiz2 is a character array with a size of 15, holding the string “Sanfoundry”. It has extra space for other characters if needed.
  • quiz3 is a pointer to the string “String in C”, which is stored in read-only memory.

The printf function is used to print each string with the labels “Quiz 1”, “Quiz 2”, and “Quiz 3”.

Input and Output of Strings in C

In C, strings are character arrays that require special handling for input and output. The standard methods for string I/O are:

  • scanf() and printf()
  • gets() and puts() (but gets() is unsafe)
  • fgets() for safe input

Using printf() and scanf() in C

In C, printf() and scanf() are standard input and output functions used for displaying output and taking user input.

  • printf() is used to display a string.
  • scanf() is used to read a string.

Example: Using scanf() and printf()

#include <stdio.h>
 
int main()
{
    int score;
    char quizName[20];
 
    printf("Enter Sanfoundry quiz name: ");
    scanf("%s", quizName);
 
    printf("Enter your score: ");
    scanf("%d", &score);
 
    printf("\nQuiz: %s\n", quizName);
    printf("Your Score: %d\n", score);
 
    return 0;
}

Input:

Enter Sanfoundry quiz name: C_Programming
Enter your score: 90

Output:

Quiz: C_Programming
Your Score: 90

This C program lets the user enter a quiz name and score. It first asks for the quiz name and stores it in the quizName array. Then, it asks for the score and stores it in the score variable. Finally, the program displays the quiz name and score on the screen.

Using gets() and puts() in C

In C, gets() and puts() are used for handling string input and output. Due to security risks, the gets() function in C is unsafe and has been deprecated. Instead, you should use fgets(), which provides better control over input size and prevents buffer overflow.

  • gets() reads the entire line, including spaces.
  • puts() prints the string and automatically adds a newline (\n).

Example: Using gets() and puts()

#include <stdio.h>
 
int main()
{
    char quizTopic[100];
 
    printf("Enter the Sanfoundry quiz topic: ");
    gets(quizTopic);  // Accepts input with spaces
 
    puts("\nQuiz Topic Entered:");
    puts(quizTopic);  // Displays the entered topic
 
    return 0;
}

Example Input:

Enter the Sanfoundry quiz topic: C Programming Basics

Output:

Quiz Topic Entered:
C Programming Basics

This C program allows the user to input a quiz topic, including spaces. It declares a character array quizTopic to store the input. The program uses the gets function to read the quiz topic, which allows spaces in the input. After the input is entered, the program uses puts to display the entered quiz topic on the screen.

fgets() in C

The fgets() function in C is used for safely reading a string from the standard input (stdin) or a file. It is the recommended alternative to gets() because it prevents buffer overflow by limiting the number of characters read.

Syntax:

char* fgets(char* str, int n, FILE* stream);

Parameters:

  • str → The character array where input is stored.
  • n → Maximum number of characters to read (including \0).
  • stream → The input source (usually stdin for keyboard input).

Example:

#include <stdio.h>
 
int main()
{
    char topic[100];
 
    printf("Enter the Sanfoundry quiz topic: ");
    fgets(topic, sizeof(topic), stdin);
 
    // Remove newline character
    topic[strcspn(topic, "\n")] = '\0';
 
    printf("Quiz Topic Entered: %s\n", topic);
    return 0;
}

Example Input:

Enter the Sanfoundry quiz topic: C Programming

Output:

Quiz Topic Entered: C Programming

This C program lets the user enter a quiz topic with spaces. It stores the input in the topic array using fgets. The program then removes the newline character added by fgets. Finally, it shows the entered quiz topic on the screen.

String Manipulation Functions in C

Here’s the list of String Manipulation Functions in C:

Function Description Example Usage
strlen(str) Returns the length of the string (excluding \0). int len = strlen(“Hello”);
strcpy(dest, src) Copies src into dest (unsafe if dest is smaller). strcpy(dest, “C Language”);
strncpy(dest, src, n) Copies at most n characters from src to dest. strncpy(dest, “C Language”, 5);
strcat(dest, src) Appends src to dest (unsafe if dest is small). strcat(str1, str2);
strncat(dest, src, n) Appends at most n characters from src to dest. strncat(str1, str2, 3);
strcmp(str1, str2) Compares two strings lexicographically. int res = strcmp(“apple”, “banana”);
strncmp(str1, str2, n) Compares the first n characters of two strings. strncmp(“apple”, “apricot”, 3);
strchr(str, ch) Finds the first occurrence of ch in str. char *ptr = strchr(“Hello”, ‘e’);
strrchr(str, ch) Finds the last occurrence of ch in str. char *ptr = strrchr(“Hello”, ‘l’);
strstr(str, substr) Finds the first occurrence of substr in str. char *ptr = strstr(“Hello World”, “World”);
strtok(str, delim) Splits str into tokens based on delim. char *token = strtok(str, “,”);
toupper(ch) Converts a character to uppercase (from <ctype.h>). char upper = toupper(‘a’);
tolower(ch) Converts a character to lowercase (from <ctype.h>). char lower = tolower(‘A’);

Finding String Length (strlen()) in C

Finds the number of characters in a string (excluding the null terminator \0).

Syntax:

size_t strlen(const char *str);

Example:

#include <stdio.h>
#include <string.h>
 
int main() {
    char str[] = "Sanfoundry";
    printf("Length of the string: %lu\n", strlen(str));
    return 0;
}

Output:

Length of the string: 10

This C program shows how to find the length of a string. It declares a string str with the value “Sanfoundry”. The program uses the strlen function to calculate the length of the string and prints the result on the screen.

Copying Strings (strcpy()) in C

Copies one string into another.

Syntax:

char* strcpy(char *destination, const char *source);

Example:

#include <stdio.h>
#include <string.h>
 
int main()
{
    char src[] = "C Programming";
    char dest[50];
 
    strcpy(dest, src);
    printf("Copied String: %s\n", dest);
    return 0;
}

Output:

Copied String: C Programming

This C program demonstrates how to copy a string. It declares a source string src with the value “C Programming” and a destination array dest with enough space to hold the string. The program uses the strcpy function to copy the content of src into dest. Finally, it prints the copied string on the screen.

Concatenating Strings (strcat()) in C

Appends one string to another.

Syntax:

char* strcat(char *destination, const char *source);

Example:

#include <stdio.h>
#include <string.h>
 
int main()
{
    char str1[50] = "Hello, ";
    char str2[] = "Sanfoundry!";
 
    strcat(str1, str2);
    printf("Concatenated String: %s\n", str1);
    return 0;
}

Output:

Concatenated String: Hello, Sanfoundry!

This C program demonstrates how to concatenate two strings. It declares str1 with the value “Hello, ” and str2 with “Sanfoundry!”. The program uses the strcat function to append str2 to str1. Finally, it prints the concatenated string on the screen.

Searching for a Character (strchr()) in C

Finds the first occurrence of a character in a string.

Syntax:

char* strchr(const char *str, int ch);

Example:

#include <stdio.h>
#include <string.h>
 
int main()
{
    char text[] = "Sanfoundry Quiz";
    char *pos = strchr(text, 'Q');
 
    if (pos != NULL)
        printf("Character found at position: %ld\n", pos - text);
    else
        printf("Character not found.\n");
 
    return 0;
}

Output:

Character found at position: 10

This C program shows how to find the position of a character in a string. It declares a string text with the value “Sanfoundry Quiz”. The program uses the strchr function to search for the character ‘Q‘. If the character is found, it prints the position of the character in the string. If the character is not found, it prints a message saying the character was not found.

Finding a Substring (strstr()) in C

Finds the first occurrence of a substring in a string.

Syntax:

char* strstr(const char *str, const char *substr);

Example:

#include <stdio.h>
#include <string.h>
 
int main()
{
    char text[] = "Learn C Programming at Sanfoundry!";
    char *pos = strstr(text, "Programming");
 
    if (pos != NULL)
        printf("Substring found at position: %ld\n", pos - text);
    else
        printf("Substring not found.\n");
 
    return 0;
}

Output:

Substring found at position: 8

This C program finds the position of a substring in a string. It stores the string “Learn C Programming at Sanfoundry!” in the variable text. The program uses strstr to search for the substring “Programming”. If the substring is found, it shows the position where it starts. If not, it prints a message saying the substring is not found.

Reversing a String (strrev()) in C

Reverses the given string.

Syntax:

char* strrev(char *str);

Example:

#include <stdio.h>
#include <string.h>
 
int main()
{
    char text[] = "Sanfoundry";
    printf("Reversed: %s\n", strrev(text));
    return 0;
}

Output:

Reversed: yrduofnaS

This C program reverses a string. It stores the string “Sanfoundry” in the variable text. The program uses the strrev function to reverse the string. Finally, it prints the reversed string on the screen.

Differences Between Strings and Character Arrays in C

Here’s the key differences between Strings and Character Arrays in C:

Aspect String Character Array
Definition A sequence of characters ending with a null character ‘\0’. A collection of characters stored in contiguous memory locations.
Null Terminator Always ends with ‘\0’ to indicate the end of the string. Does not necessarily end with ‘\0’ unless explicitly assigned.
Declaration char str[] = “Hello”; char arr[] = {‘H’, ‘e’, ‘l’, ‘l’, ‘o’};
Memory Allocation Can be declared as an array or a pointer. Only declared as an array.
Modification Can be modified if stored in a character array. Can modify individual characters, but if a string is assigned directly, modifying is unsafe.
Accessing Elements Can be accessed using array indexing or pointer notation. Accessed using array indexing only.
Operations Supports standard string functions like strlen(), strcpy(), strcat(). Does not support string functions unless explicitly terminated with ‘\0’.
Example Usage char str[] = “Hello”; char arr[] = {‘H’, ‘e’, ‘l’, ‘l’, ‘o’};

FAQs on Strings in C

1. What is a string in C?
A string in C is a sequence of characters stored in a character array, ending with a null character (\0).

2. How do you declare and initialize a string in C?
Strings can be declared using character arrays or pointers and initialized using double quotes or character lists.

3. What is the difference between a character array and a string?
A character array is a collection of characters, whereas a string is a character array that ends with a null terminator (\0).

4. Can we modify a string literal in C?
No, string literals are stored in read-only memory, and modifying them leads to undefined behavior.

5. How do you take string input in C?
String input can be taken using functions like scanf() and fgets(). scanf() does not read spaces, while fgets() reads the entire line.

6. What happens if a string is not null-terminated?
Without a null terminator, string functions may read beyond the allocated memory, leading to undefined behavior.

7. How do you dynamically allocate memory for a string?
Memory for a string can be allocated using dynamic memory functions like malloc() and calloc().

8. How do you concatenate two strings safely?
Using strncat() ensures that only a limited number of characters are appended, preventing buffer overflow.

9. How do you compare two strings in C?
The strcmp() function is used for comparison. A return value of 0 indicates that the strings are equal.

Key Points to Remember

Here is the list of key points we need to remember about “Strings in C”.

  • Strings in C are arrays of characters, terminated by a null character (\0).
  • Strings can be declared using character arrays (with or without an explicit size) or pointers, but modifying strings declared with a pointer to a string literal is unsafe.
  • scanf() and printf() are used for basic input/output, while gets() (unsafe) and puts() handle string input/output. fgets() is a safer alternative to gets().
  • Functions like strlen(), strcpy(), strcat(), and strcmp() allow common operations such as measuring string length, copying, concatenating, and comparing strings.
  • strlen() is used to find the length of a string, excluding the null terminator (\0).
  • strcpy() is used to copy one string into another. Ensure that the destination array is large enough to hold the copied string.
  • strcat() appends one string to another, but care must be taken to ensure there is enough space in the destination array.
  • Strings end with a null character (\0), while character arrays may not. Strings are easier to manipulate using built-in functions, whereas character arrays require explicit handling of the null terminator.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.