0% found this document useful (0 votes)
5 views13 pages

Strings in C

In C, strings are arrays of characters terminated by a null character '\0', and there is no built-in string data type. Common operations include accessing characters, reading input, and using string functions like strlen(), strcpy(), strcat(), and strcmp(). String literals are read-only and should be assigned to const char* for safety, while care must be taken to avoid buffer overflows when manipulating strings.

Uploaded by

shawsubham285
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views13 pages

Strings in C

In C, strings are arrays of characters terminated by a null character '\0', and there is no built-in string data type. Common operations include accessing characters, reading input, and using string functions like strlen(), strcpy(), strcat(), and strcmp(). String literals are read-only and should be assigned to const char* for safety, while care must be taken to avoid buffer overflows when manipulating strings.

Uploaded by

shawsubham285
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Strings in C

Last Updated : 14 Nov, 2025

A string is an array of characters terminated by a special character '\0' (null character). This null
character marks the end of the string and is essential for proper string manipulation.

Unlike many modern languages, C does not have a built-in string data type. Instead, strings are
implemented as arrays of char.

S#include <stdio.h>

int main() {

// declaring and initializing a string

char str[] = "Geeks";

// printing the string

printf("The string is: %s\n", str);

return 0;

Output

The string is: Geeks

• char str[] = "Geeks";


This line declares a character array str and initializes it with the string "Geeks". Internally,
this creates an array like:
{ 'G', 'e', 'e', 'k', 's', '\0'}
The null character '\0' is automatically added at the end to terminate the string.

• printf("The string is: %s\n", str);


%s is the format specifier used to print a string. printf starts at the memory location
of str and prints each character until it finds the terminating null character '\0'.

Accessing Characters

• A string in C is an array of characters ending with \0.

• We can access any character of the string by providing the position of the character, like
in array.

#include <stdio.h>

int main() {

char str[] = "Geeks";


// Access first character

// of string

printf("%c", str[0]);

return 0;

Output

Update

We can change individual characters of a string using their index: str[0] = 'h'. Strings can
also be updated using standard library functions like strcpy() to replace the entire string.
Ensure the new string fits within the allocated array size to avoid memory issues.

#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 in C, you need to iterate through each character until you
reach the null terminator '\0', which marks the end of the string. This process is handled
efficiently by the strlen() function from the C standard library.

#include <stdio.h>

int main() {

char str[] = "Geeks";

printf("%d", strlen(str));

return 0;

Output

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

C language also provides several other useful string library functions to perform
operations like copying, comparing, and concatenating strings. You can refer to standard
string functions for more details.

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.

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

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

#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:

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

#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
So far, we've seen how to declare and use strings as character arrays. But in C, strings can also
be represented using string literals, which offer a simpler way to initialize strings directly in the
code. Let's understand what string literals are and how they work.

Strings Literals

A string literal is a sequence of characters enclosed in double quotes, like "Hello" or "1234".
Internally, it is stored as a constant character array terminated by a null character '\0'.

#include <stdio.h>

int main() {

// pointer to a string literal

const char *str = "Hello World";

printf("%s\n", str);

return 0;

}
Output

Hello World

• "Hello World" is a string literal. It is stored in a read-only section of memory.

• const char *str = "Hello World";


This creates a pointer to the string literal. Using const is important because string
literals should not be modified.

• printf("%s\n", str); prints the string starting from the address stored in str.

Key Points

• String literals are automatically null-terminated.

• They are typically stored in read-only memory, so modifying them causes undefined
behavior.

• You can assign string literals to char*, but it's recommended to use const char* for
safety.

In C, strings aren't a built-in data type like int or float. Instead, they are simply arrays of
characters that end with a special "null terminator" character (\0). To handle these effectively, C
provides the <string.h> header file, which contains a suite of powerful functions.

Core String Functions

The following functions are the "big four" you will use most often:

Function Purpose Syntax Example

strlen() Finds the length of a string (excluding \0) int len = strlen(str);

strcpy(destination,
strcpy() Copies one string into another
source);

Appends (concatenates) one string to the end of


strcat() strcat(first, second);
another
Function Purpose Syntax Example

strcmp() Compares two strings lexicographically int result = strcmp(s1, s2);

1. strlen() — Length of a String

This function counts the number of characters in a string until it hits the \0.

• Note: It does not count the null terminator itself.

2. strcpy() — Copying Strings

Since you can't simply use the = operator to copy strings in C (e.g., str1 = str2 is invalid for
arrays), you use strcpy.

• Warning: Ensure the destination array is large enough to hold the source string, or you'll
cause a buffer overflow.

3. strcat() — Concatenation

This joins two strings together. It finds the \0 of the first string and starts writing the second
string over it.

4. strcmp() — Comparison

This function compares two strings character by character.

• Returns 0 if the strings are identical.

• Returns a positive value if the first string is greater (alphabetically later).

• Returns a negative value if the first string is smaller.

Implementation Example

#include <stdio.h>

#include <string.h>

int main() {
char str1[20] = "Hello";

char str2[20] = "World";

char str3[40];

// 1. Length

printf("Length of str1: %zu\n", strlen(str1));

// 2. Copy

strcpy(str3, str1);

printf("str3 after copy: %s\n", str3);

// 3. Concatenate

strcat(str1, " ");

strcat(str1, str2);

printf("str1 after concatenation: %s\n", str1);

// 4. Compare

if (strcmp(str1, "Hello World") == 0) {

printf("The strings match!\n");

return 0;

Important Guardrails

• Buffer Overflow: C does not check if your array is big enough. If you strcat a long string
into a small array, it will overwrite other memory, often crashing your program.
• The Null Terminator: Always remember that a string of length 10 actually needs an array
of size 11 to accommodate the \0.

You might also like