C String – How to Declare Strings in the C Programming Language

Dionysia Lemonaki

Computers store and process all kinds of data.

Strings are just one of the many forms in which information is presented and gets processed by computers.

Strings in the C programming language work differently than in other modern programming languages.

In this article, you'll learn how to declare strings in C.

Before doing so, you'll go through a basic overview of what data types, variables, and arrays are in C. This way, you'll understand how these are all connected to one another when it comes to working with strings in C.

Knowing the basics of those concepts will then help you better understand how to declare and work with strings in C.

Let's get started!

Data types in C

C has a few built-in data types.

They are int , short , long , float , double , long double and char .

As you see, there is no built-in string or str (short for string) data type.

The char data type in C

From those types you just saw, the only way to use and present characters in C is by using the char data type.

Using char , you are able to to represent a single character – out of the 256 that your computer recognises. It is most commonly used to represent the characters from the ASCII chart.

The single characters are surrounded by single quotation marks .

The examples below are all char s – even a number surrounded by single quoation marks and a single space is a char in C:

Every single letter, symbol, number and space surrounded by single quotation marks is a single piece of character data in C.

What if you want to present more than one single character?

The following is not a valid char – despite being surrounded by single quotation marks. This is because it doesn't include only a single character inside the single quotation marks:

'freeCodeCamp is awesome'

When many single characters are strung together in a group, like the sentence you see above, a string is created. In that case, when you are using strings, instead of single quotation marks you should only use double quotation marks.

"freeCodeCamp is awesome"

How to declare variables in C

So far you've seen how text is presented in C.

What happens, though, if you want to store text somewhere? After all, computers are really good at saving information to memory for later retrieval and use.

The way you store data in C, and in most programming languages, is in variables.

Essentially, you can think of variables as boxes that hold a value which can change throughout the life of a program. Variables allocate space in the computer's memory and let C know that you want some space reserved.

C is a statically typed language, meaning that when you create a variable you have to specify what data type that variable will be.

There are many different variable types in C, since there are many different kinds of data.

Every variable has an associated data type.

When you create a variable, you first mention the type of the variable (wether it will hold integer, float, char or any other data values), its name, and then optionally, assign it a value:

Be careful not to mix data types when working with variables in C, as that will cause errors.

For intance, if you try to change the example from above to use double quotation marks (remember that chars only use single quotation marks), you'll get an error when you compile the code:

As mentioned earlier on, C doesn't have a built-in string data type. That also means that C doesn't have string variables!

How to create arrays in C

An array is essentially a variable that stores multiple values. It's a collection of many items of the same type.

As with regular variables, there are many different types of arrays because arrays can hold only items of the same data type. There are arrays that hold only int s, only float s, and so on.

This is how you define an array of ints s for example:

First you specify the data type of the items the array will hold. Then you give it a name and immediately after the name you also include a pair of square brackets with an integer. The integer number speficies the length of the array.

In the example above, the array can hold 3 values.

After defining the array, you can assign values individually, with square bracket notation, using indexing. Indexing in C (and most programming languages) starts at 0 .

You reference and fetch an item from an array by using the name of the array and the item's index in square brackets, like so:

What are character arrays in C?

So, how does everything mentioned so far fit together, and what does it have to do with initializing strings in C and saving them to memory?

Well, strings in C are actually a type of array – specifically, they are a character array . Strings are a collection of char values.

How strings work in C

In C, all strings end in a 0 . That 0 lets C know where a string ends.

That string-terminating zero is called a string terminator . You may also see the term null zero used for this, which has the same meaning.

Don't confuse this final zero with the numeric integer 0 or even the character '0' - they are not the same thing.

The string terminator is added automatically at the end of each string in C. But it is not visible to us – it's just always there.

The string terminator is represented like this: '\0' . What sets it apart from the character '0' is the backslash it has.

When working with strings in C, it's helpful to picture them always ending in null zero and having that extra byte at the end.

Screenshot-2021-10-04-at-8.46.08-PM

Each character takes up one byte in memory.

The string "hello" , in the picture above, takes up 6 bytes .

"Hello" has five letters, each one taking up 1 byte of space, and then the null zero takes up one byte also.

The length of strings in C

The length of a string in C is just the number of characters in a word, without including the string terminator (despite it always being used to terminate strings).

The string terminator is not accounted for when you want to find the length of a string.

For example, the string freeCodeCamp has a length of 12 characters.

But when counting the length of a string, you must always count any blank spaces too.

For example, the string I code has a length of 6 characters. I is 1 character, code has 4 characters, and then there is 1 blank space.

So the length of a string is not the same number as the number of bytes that it has and the amount of memory space it takes up.

How to create character arrays and initialize strings in C

The first step is to use the char data type. This lets C know that you want to create an array that will hold characters.

Then you give the array a name, and immediatelly after that you include a pair of opening and closing square brackets.

Inside the square brackets you'll include an integer. This integer will be the largest number of characters you want your string to be including the string terminator.

You can initialise a string one character at a time like so:

But this is quite time-consuming. Instead, when you first define the character array, you have the option to assign it a value directly using a string literal in double quotes:

If you want, istead of including the number in the square brackets, you can only assign the character array a value.

It works exactly the same as the example above. It will count the number of characters in the value you provide and automatically add the null zero character at the end:

Remember, you always need to reserve enough space for the longest string you want to include plus the string terminator.

If you want more room, need more memory, and plan on changing the value later on, include a larger number in the square brackets:

How to change the contents of a character array

So, you know how to initialize strings in C. What if you want to change that string though?

You cannot simply use the assignment operator ( = ) and assign it a new value. You can only do that when you first define the character array.

As seen earlier on, the way to access an item from an array is by referencing the array's name and the item's index number.

So to change a string, you can change each character individually, one by one:

That method is quite cumbersome, time-consuming, and error-prone, though. It definitely is not the preferred way.

You can instead use the strcpy() function, which stands for string copy .

To use this function, you have to include the #include <string.h> line after the #include <stdio.h> line at the top of your file.

The <string.h> file offers the strcpy() function.

When using strcpy() , you first include the name of the character array and then the new value you want to assign. The strcpy() function automatically add the string terminator on the new string that is created:

And there you have it. Now you know how to declare strings in C.

To summarize:

  • C does not have a built-in string function.
  • To work with strings, you have to use character arrays.
  • When creating character arrays, leave enough space for the longest string you'll want to store plus account for the string terminator that is included at the end of each string in C.
  • Define the array and then assign each individual character element one at a time.
  • OR define the array and initialize a value at the same time.
  • When changing the value of the string, you can use the strcpy() function after you've included the <string.h> header file.

If you want to learn more about C, I've written a guide for beginners taking their first steps in the language.

It is based on the first couple of weeks of CS50's Introduction to Computer Science course and I explain some fundamental concepts and go over how the language works at a high level.

You can also watch the C Programming Tutorial for Beginners on freeCodeCamp's YouTube channel.

Thanks for reading and happy learning :)

Read more posts .

If this article was helpful, share it .

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

01 Career Opportunities

02 beginner, 03 intermediate, 04 advanced, 05 training programs, strings in c with examples: string functions, free c programming online course with certificate, strings in c: an overview, what are strings in c, how to declare a string in c, how to initialize a string in c, using char array, using string literal, string program in c compiler, how to access a string in c, how to modify a string in c, how to loop through a string in c, string functions in c, example to demonstrate some basic string functions in c online compiler, live classes schedule.

Filling Fast
Filling Fast
Filling Fast
Filling Fast
Filling Fast
Filling Fast
Filling Fast
Filling Fast
Filling Fast
Filling Fast
Filling Fast
Filling Fast
Filling Fast
Filling Fast

About Author

Next: Execution Control Expressions , Previous: Arithmetic , Up: Top   [ Contents ][ Index ]

7 Assignment Expressions

As a general concept in programming, an assignment is a construct that stores a new value into a place where values can be stored—for instance, in a variable. Such places are called lvalues (see Lvalues ) because they are locations that hold a value.

An assignment in C is an expression because it has a value; we call it an assignment expression . A simple assignment looks like

We say it assigns the value of the expression value-to-store to the location lvalue , or that it stores value-to-store there. You can think of the “l” in “lvalue” as standing for “left,” since that’s what you put on the left side of the assignment operator.

However, that’s not the only way to use an lvalue, and not all lvalues can be assigned to. To use the lvalue in the left side of an assignment, it has to be modifiable . In C, that means it was not declared with the type qualifier const (see const ).

The value of the assignment expression is that of lvalue after the new value is stored in it. This means you can use an assignment inside other expressions. Assignment operators are right-associative so that

is equivalent to

This is the only useful way for them to associate; the other way,

would be invalid since an assignment expression such as x = y is not valid as an lvalue.

Warning: Write parentheses around an assignment if you nest it inside another expression, unless that is a conditional expression, or comma-separated series, or another assignment.

  The basics of storing a value.
  Expressions into which a value can be stored.
  Shorthand for changing an lvalue’s contents.
  Shorthand for incrementing and decrementing an lvalue’s contents.
  Accessing then incrementing or decrementing.
  How to avoid ambiguity.
  Write assignments as separate statements.

C Functions

C structures, c reference.

Strings are used for storing text/characters.

For example, "Hello World" is a string of characters.

Unlike many other programming languages, C does not have a String type to easily create string variables. Instead, you must use the char type and create an array of characters to make a string in C:

Note that you have to use double quotes ( "" ).

To output the string, you can use the printf() function together with the format specifier %s to tell C that we are now working with strings:

Access Strings

Since strings are actually arrays in C, you can access a string by referring to its index number inside square brackets [] .

This example prints the first character (0) in greetings :

Note that we have to use the %c format specifier to print a single character .

Modify Strings

To change the value of a specific character in a string, refer to the index number, and use single quotes :

Advertisement

Loop Through a String

You can also loop through the characters of a string, using a for loop:

And like we specified in the arrays chapter, you can also use the sizeof formula (instead of manually write the size of the array in the loop condition (i < 5) ) to make the loop more sustainable:

Another Way Of Creating Strings

In the examples above, we used a "string literal" to create a string variable. This is the easiest way to create a string in C.

You should also note that you can create a string with a set of characters. This example will produce the same result as the example in the beginning of this page:

Why do we include the \0 character at the end? This is known as the "null terminating character", and must be included when creating strings using this method. It tells C that this is the end of the string.

Differences

The difference between the two ways of creating strings, is that the first method is easier to write, and you do not have to include the \0 character, as C will do it for you.

You should note that the size of both arrays is the same: They both have 13 characters (space also counts as a character by the way), including the \0 character:

Real-Life Example

Use strings to create a simple welcome message:

C Exercises

Test yourself with exercises.

Fill in the missing part to create a "string" named greetings , and assign it the value "Hello".

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

Guru99

Strings in C: How to Declare & Initialize a String Variables in C

Benjamin Walker

What is String in C?

A String in C is nothing but a collection of characters in a linear sequence. ‘C’ always treats a string a single data even though it contains whitespaces. A single character is defined using single quote representation. A string is represented using double quote marks.

‘C’ provides standard library <string.h> that contains many functions which can be used to perform complicated operations easily on Strings in C.

How to Declare a String in C?

A C String is a simple array with char as a data type. ‘C’ language does not directly support string as a data type. Hence, to display a String in C, you need to make use of a character array.

The general syntax for declaring a variable as a String in C is as follows,

The classic Declaration of strings can be done as follow:

The size of an array must be defined while declaring a C String variable because it is used to calculate how many characters are going to be stored inside the string variable in C. Some valid examples of string declaration are as follows,

The above example represents string variables with an array size of 15. This means that the given C string array is capable of holding 15 characters at most. The indexing of array begins from 0 hence it will store characters from a 0-14 position. The C compiler automatically adds a NULL character ‘\0’ to the character array created.

How to Initialize a String in C?

Let’s study the String initialization in C. Following example demonstrates the initialization of Strings in C,

In string3, the NULL character must be added explicitly, and the characters are enclosed in single quotation marks.

‘C’ also allows us to initialize a string variable without defining the size of the character array. It can be done in the following way,

The name of Strings in C acts as a pointer because it is basically an array.

C String Input: C Program to Read String

When writing interactive programs which ask the user for input, C provides the scanf(), gets(), and fgets() functions to find a line of text entered from the user.

When we use scanf() to read, we use the “%s” format specifier without using the “&” to access the variable address because an array name acts as a pointer. For example:

The problem with the scanf function is that it never reads entire Strings in C. It will halt the reading process as soon as whitespace, form feed, vertical tab, newline or a carriage return occurs. Suppose we give input as “Guru99 Tutorials” then the scanf function will never read an entire string as a whitespace character occurs between the two names. The scanf function will only read Guru99 .

RELATED ARTICLES

  • Powershell Tutorial for Beginners: Learn Powershell Scripting
  • What is C Programming Language? Basics, Introduction, History

In order to read a string contains spaces, we use the gets() function. Gets ignores the whitespaces. It stops

reading when a newline is reached (the Enter key is pressed).

For example:

Another safer alternative to gets() is fgets() function which reads a specified number of characters. For example:

The fgets() arguments are :

  • the string name,
  • the number of characters to read,
  • stdin means to read from the standard input which is the keyboard.

C String Output: C program to Print a String

The standard printf function is used for printing or displaying Strings in C on an output device. The format specifier used is %s

String output is done with the fputs() and printf() functions.

fputs() function

The fputs() needs the name of the string and a pointer to where you want to display the text. We use stdout which refers to the standard output in order to print to the screen. For example:

puts function

The puts function is used to Print string in C on an output device and moving the cursor back to the first position. A puts function can be used in the following way,

The syntax of this function is comparatively simple than other functions.

The string library

The standard ‘C’ library provides various functions to manipulate the strings within a program. These functions are also called as string handlers. All these handlers are present inside <string.h> header file.

Function Purpose
This function is used for finding a length of a string. It returns how many characters are present in a string excluding the NULL character.
This function is used for combining two strings together to form a single string. It Appends or concatenates str2 to the end of str1 and returns a pointer to str1.
This function is used to compare two strings with each other. It returns 0 if str1 is equal to str2, less than 0 if str1 < str2, and greater than 0 if str1 > str2.

Lets consider the program below which demonstrates string library functions:

Other important library functions are:

  • strncmp(str1, str2, n) :it returns 0 if the first n characters of str1 is equal to the first n characters of str2, less than 0 if str1 < str2, and greater than 0 if str1 > str2.
  • strncpy(str1, str2, n) This function is used to copy a string from another string. Copies the first n characters of str2 to str1
  • strchr(str1, c): it returns a pointer to the first occurrence of char c in str1, or NULL if character not found.
  • strrchr(str1, c): it searches str1 in reverse and returns a pointer to the position of char c in str1, or NULL if character not found.
  • strstr(str1, str2): it returns a pointer to the first occurrence of str2 in str1, or NULL if str2 not found.
  • strncat(str1, str2, n) Appends (concatenates) first n characters of str2 to the end of str1 and returns a pointer to str1.
  • strlwr() :to convert string to lower case
  • strupr() :to convert string to upper case
  • strrev() : to reverse string

Converting a String to a Number

In C programming, we can convert a string of numeric characters to a numeric value to prevent a run-time error. The stdio.h library contains the following functions for converting a string to a number:

  • int atoi(str) Stands for ASCII to integer; it converts str to the equivalent int value. 0 is returned if the first character is not a number or no numbers are encountered.
  • double atof(str) Stands for ASCII to float, it converts str to the equivalent double value. 0.0 is returned if the first character is not a number or no numbers are encountered.
  • long int atol(str) Stands for ASCII to long int, Converts str to the equivalent long integer value. 0 is returned if the first character is not a number or no numbers are encountered.

The following program demonstrates atoi() function:

  • A string pointer declaration such as char *string = “language” is a constant and cannot be modified.
  • A string is a sequence of characters stored in a character array.
  • A string is a text enclosed in double quotation marks.
  • A character such as ‘d’ is not a string and it is indicated by single quotation marks.
  • ‘C’ provides standard library functions to manipulate strings in a program. String manipulators are stored in <string.h> header file.
  • A string must be declared or initialized before using into a program.
  • There are different input and output string functions, each one among them has its features.
  • Don’t forget to include the string library to work with its functions
  • We can convert string to number through the atoi(), atof() and atol() which are very useful for coding and decoding processes.
  • We can manipulate different strings by defining a array of strings in C.

You Might Like:

Top 100 C Programming Interview Questions and Answers (PDF)

Learn C practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn c interactively, c introduction.

  • Getting Started with C
  • Your First C Program

C Fundamentals

  • C Variables, Constants and Literals
  • C Data Types
  • C Input Output (I/O)
  • C Programming Operators

C Flow Control

  • C if...else Statement
  • C while and do...while Loop
  • C break and continue
  • C switch Statement
  • C goto Statement

C Functions

  • C User-defined functions
  • Types of User-defined Functions in C Programming
  • C Recursion
  • C Storage Class

C Programming Arrays

  • C Multidimensional Arrays
  • Pass arrays to a function in C

C Programming Pointers

  • Relationship Between Arrays and Pointers
  • C Pass Addresses and Pointers
  • C Dynamic Memory Allocation
  • C Array and Pointer Examples

C Programming Strings

String Manipulations In C Programming Using Library Functions

String Examples in C Programming

C Structure and Union

  • C structs and Pointers
  • C Structure and Function

C Programming Files

  • C File Handling
  • C Files Examples

C Additional Topics

  • C Keywords and Identifiers
  • C Precedence And Associativity Of Operators
  • C Bitwise Operators
  • C Preprocessor and Macros

C Standard Library Functions

C Tutorials

  • Concatenate Two Strings
  • Sort Elements in Lexicographical Order (Dictionary Order)

You need to often manipulate strings according to the need of a problem. Most, if not all, of the time string manipulation can be done manually but, this makes programming complex and large.

To solve this, C supports a large number of string handling functions in the standard library "string.h" .

Few commonly used string handling functions are discussed below:

Function Work of Function
computes string's length
copies a string to another
concatenates(joins) two strings
compares two strings
strlwr() converts string to lowercase
strupr() converts string to uppercase

String handling functions are defined under "string.h" header file.

Note: You have to include the code below to run string handling functions.

gets() and puts()

Functions gets() and puts() are two string functions to take string input from the user and display it respectively as mentioned in the  previous chapter .

Note: Though, gets() and puts() function handle strings, both these functions are defined in "stdio.h" header file.

Video: C String Functions

Sorry about that.

Our premium learning platform, created with over a decade of experience and thousands of feedbacks .

Learn and improve your coding skills like never before.

  • Interactive Courses
  • Certificates
  • 2000+ Challenges

Related Tutorials

IncludeHelp_logo

  • Data Structure
  • Coding Problems
  • C Interview Programs
  • C++ Aptitude
  • Java Aptitude
  • C# Aptitude
  • PHP Aptitude
  • Linux Aptitude
  • DBMS Aptitude
  • Networking Aptitude
  • AI Aptitude
  • MIS Executive
  • Web Technologie MCQs
  • CS Subjects MCQs
  • Databases MCQs
  • Programming MCQs
  • Testing Software MCQs
  • Digital Mktg Subjects MCQs
  • Cloud Computing S/W MCQs
  • Engineering Subjects MCQs
  • Commerce MCQs
  • More MCQs...
  • Machine Learning/AI
  • Operating System
  • Computer Network
  • Software Engineering
  • Discrete Mathematics
  • Digital Electronics
  • Data Mining
  • Embedded Systems
  • Cryptography
  • CS Fundamental
  • More Tutorials...
  • Tech Articles
  • Code Examples
  • Programmer's Calculator
  • XML Sitemap Generator
  • Tools & Generators

IncludeHelp

  • C - Getting Started
  • C - Overview
  • C - Advantages & Disadvantages
  • C - Character Set
  • Gcc Vs. G++
  • Why We should Use C?
  • C - Basic Rules
  • C - Comments
  • C - Variable Naming Conventions
  • C - Variable Initialization
  • C - Constants
  • C - Character Constant
  • C - Octal Literals
  • C - Hexadecimal Literals
  • C - Automatic (auto) Variables
  • Local Vs. Global Variables
  • C - Access Global Variables
  • Is exit() & return Statements are Same?
  • C - Print Float Value
  • C - Print Multiple Lines Using printf()
  • C - Argument Index Specification
  • C - Value Returned by scanf()
  • C - Returned Values of printf() & scanf()
  • What do 'lvalue' & 'rvalue' Mean
  • Automatic (auto) Vs. Static Variables

C Data Types

  • C - Data Types & Operators
  • C - Basic Data Types
  • C - 'unsigned char' For Memory Optimization
  • short Vs. short int Vs. int
  • unsigned int Vs. size_t
  • C - Storage Classes Introduction
  • C - Storage Classes With Examples
  • C- Type Conversion
  • C - Type Qualifiers

C Input/Output

  • C - Read String With Spaces
  • C - Input String of Unknown Length
  • C - Disadvantages of scanf()
  • C - scanf() need '%lf' for doubles, when printf() is okay with just '%f'
  • C - Format Specifier for unsigned short int
  • C - printf() Format Specifier for bool
  • C - printf() Arguments for long
  • C - printf() Specifier for double
  • Is there a printf() converter to print in binary format?
  • C - Nested printf()
  • printf() Vs. puts()
  • printf() Vs. sprintf()
  • %d Vs. %i format Specifiers
  • C - Single Character Input & Output
  • C- Formatted Input & Output
  • C - Octal & Hex Escape Sequences
  • C - Convert Float to String
  • gets() Vs. fgets()
  • C - Input Unsigned Integer Value
  • C - Input Octal Value
  • C - Input Hex Value
  • C - Input Decimal, Octal & Hex in char Variables
  • C - Input With '%i'
  • C - Input Individual Characters
  • C - Skip characters While Reading Integers
  • C - Read Memory Address
  • C - Printing Variable's Address
  • C - printf() Examples & Variations

C Operators

  • C - Operators Precedence & Associativity
  • Operators Vs. Operands
  • C - Unary Operators
  • C - Equality Operators
  • C - Logical AND (&&) Operator
  • C - Logical OR (||) Operator
  • C - Logical NOT (!) Operator
  • C - Modulus on Negative Numbers
  • C - Expression a=b=c (Multiple Assignment) Evaluates
  • C - Expression a==b==c (Multiple Comparison) Evaluates
  • C - Complex Return Statement Using Comma Operator
  • C - Comma Operator
  • C - Bitwise Operators
  • C - Bitwise One's Compliment
  • C - Modulus of Float or Double Numbers

C Conditional Statements

  • C - If Else Statements
  • C - Switch Case
  • C - Switch Statements Features, Disadvantages
  • C - Using Range With Switch

C Control Statements

  • C - 'goto' Statement
  • C - break & continue
  • Print Numbers From 1 to N Using goto
  • C - Looping
  • C - Looping Programs
  • C - Nested Loops
  • C - Entry Controlled Vs. Exit Controlled Loops
  • C - Sentinel Vs. Counter Controlled Loops
  • C - Use for Loop as Infinite Loop
  • C - Strings in C language programming
  • C - string.h Functions
  • C - memcpy() Function
  • C - Write Your Own memcpy()
  • C - memset() Function
  • C - Write Your Own memset()

C Functions

  • C - Library & User-define Functions
  • C - Static Functions
  • C - Scope of Function Parameters
  • C - Recursion
  • C - Recursion Examples
  • More on Arrays
  • C - Properties/Characteristics of Array

C Structure and Unions

  • C Structures
  • C - Initialize a Structure in Accordance
  • C - Size of Structure With No Members
  • C -Pointer to Structure
  • C - Nested Structure Initialization
  • C - Nested Structure With Examples
  • C - Size of Structure
  • C - Copy Complete Structure in Byte Array
  • C - Pointer to Union
  • C - Pointers
  • C - Pointer Rules
  • C - Pointers Declarations
  • C - Pointer Address Operators
  • C - Accessing Variable Using Pointer
  • C - Address of (&) & Dereference (*) Operators
  • C - NULL Pointer
  • C - Pointers as Argument
  • C - Pointer Arithmetic
  • C - Pointer to an Array
  • C - Evaluation of Statement '*ptr++'
  • C - Pointer & Non-pointer Variables Declarations Together
  • C - Pointer to an Array of Integers
  • C - Pointer to Pointer
  • C - void Pointer as Function Argument
  • char s[] Vs. char *s
  • C - Copying Integer Value to Char Buffer & Vice Versa
  • C - Call by Reference Vs. Call by Value
  • C - Typedef Function Pointer

C Preprocessor Directives

  • Recommendation for defining a macro in C language
  • Macro expansion directives (#define, #undef) in C language
  • Complex macro with arguments (function like macro) in C language
  • C language #ifdef, #else, #endif Pre-processor with Example
  • C language #if, #elif, #else, #endif Pre-processor with Example
  • Parameterized Macro - we cannot use space after the Macro Name
  • Stringizing Operator (#) in C
  • Token Pasting Directive Operator (##) in C

C Command-line Arguments

  • C language Command Line Arguments

C File Handlings

  • C - Basics of File Handling
  • C - File Handling Programs
  • C - Graphics Modes
  • C - Using Colors in Text Mode
  • C - More on Graphics Modes
  • C - OUTTEXTXY() & SETTEXTSTYLE() Functions
  • C - Draw Circle & Rectangle
  • C - graphics.h Functions
  • C - More Graphics-related Interesting Functions

C Advance Topics

  • C - Process Identification (pid_t)
  • C - getpid() & getppid()
  • C - Rrules For Writing C/C++ Program
  • C - Tips For Embedded Development
  • C - Optimization Techniques
  • C Vs. Embedded C
  • C- File Management System Calls
  • C/C++ Multithreading
  • C/C++ - Sum of Array Using Multithreading

C Tips and Tricks

  • C - Copy Two Bytes Int. to Byte Buffer
  • C - Is Pre-increment Faster than Post-increment?
  • C - Create Delay Function
  • Why should We use 'f' With Float Literal in C?
  • C - Replacing a Part of String
  • C- Comparing Number of Characters of Two Strings
  • C - Safest Way to Check Value Using ==
  • C- Check EVEN or ODD W/O % Operator
  • C- Use Single Byte to Store 8 Values
  • C- Funny Trick to Use C++ in C
  • C - Trick to Print Maximum Value of an unsigned int
  • C - Print Maximum Value of an unsigned int using One's Compliment (~) Operator in C
  • Why we should use switch instead of if else?
  • How to initialize array elements with hexadecimal values in C?
  • How should we declare/define a pointer variable?

C Important Topics

  • C - Working With Hexadecimal
  • C - Working With octal
  • C - Convert ASCII String (char[]) to BYTE Array
  • C - Convert ASCII String (char[]) to Octal String
  • C - Convert ASCII String (char[]) to Hex String
  • C - Assign Binary Calue in a Variable Directly
  • C - Check Particular Bit is SET or Not
  • C- Set, Clear, & Toggle a Bit
  • C - Value of 'EOF'
  • C - Print printf("Hello world."); Using printf()
  • C - Print Text in New Line w/O Using '\n'
  • C - Return 0 From int main()
  • 'Super Loop' Architecture for Embedded C
  • C - Executing System Commands
  • C - Infix To Postfix Conversion Using Stack
  • C - Evaluation of Postfix Expressions Using Stack
  • C - Polynomial Addition Using Structure
  • C - conio.h Functions
  • SQLite with C language
  • C - SQL Table Creation, Insertion
  • C - Aptitude Questions
  • C - Interview Questions
  • C - Find Output Programs

Advertisement

Home » C programming language

Strings in C Programming Language (With Examples)

Strings in C programming language: In this tutorial, we will learn about the strings in C, declaring, initializing, printing getting the length of the string, and many more with the help of examples. By Sneha Dujaniya Last updated : December 26, 2023

What are Strings ?

Strings are mostly considered difficult by many beginners but trust me, Strings are no big deal. A string is nothing but a group of characters stored in a character array. Character arrays are used in programming languages to manipulate words and sentences.

A string is a constant in the form of the one-dimensional array of characters terminated by a null character which is \0 . Example,

Points to be noted:

  • Memory space occupied by each character is one byte and the last character has to be null \0 .
  • \0 should not be confused with the digit 0 since the ASCII value of null is 0 whereas that of ‘0' is 48.
  • The members of the array are stored in contiguous memory locations as shown below.

string representation in C

  • The null character at the end is very important because that is the only way for the compiler to know where the string ends. But to be noted, the null declaration is not necessary. It is inserted by the compiler automatically as in the following example: char city[] = "TOKYO";
  • The format specification used for printing and receiving a string is "%s" .

Declaring String

The string is a character array. Thus, to declare a string, you need to create a character array with the maximum size of the string.

Declare a string to store a name.

Initialize String

There are multiple methods to initialize string.

1. Initialize string during declaration

You can initialize a string during declaration in the following ways:

2. Initialize string by using strcpy() or memcpy()

You cannot directly assign a string by using the assignment ( = ) operator. You can initialize a string anywhere in the program after the declaration by using either strcpy() or memcpy() function .

To use strcpy() or memcpy() function, you need to include <string.h> header file .

Printing String

To print a string in language, you can use printf() and puts() functions. The printf() function requires "%s" format specifier to display the string value whereas the puts() function just takes the string variable as an argument.

Printing String Variable Size

To print the occupied memory size (in bytes) by a string variable, you can use the sizeof() operator .

You can see, that we used "%ld" in the printf() statement. The "%ld" is a format specifier to display the long int value. The sizeof() operator returns a long integer value.

Also Read: Arguments for printf() that formats a long datatype

Getting String Length

There are two ways to get the string length: Using the strlen() method (which is a library function of string.h header), and by counting each character of the string using the loop (for that you can create a function to get the string length ).

C Strings: More Examples

Now let us see some of the examples:

Example 1: Declare string and print character by character

Simple program, where we are treating the string as a character array and we use %c in printf() statement . Also, the length of the word is taken to be 4 because the value of the first element in an array is always assigned 0 , as we all know already. But this solution is not profitable if we have a bigger string.

So, here is another way to do it:

Example 2: Declare string and print character by character till NULL not found

Example 3: declaring string and printing as string (using "%s" format specifier).

This was the simplest way to print a string using the general specification of %s .

Example 4: Reading string using scanf() function

Here, the declaration char city[15] stores 15 bytes of memory under the array city[] . Whereas, the scanf() function fills the characters entered till the enter key is pressed by the user. After that, scanf() automatically adds a null character leaving the further memory blank.

Reading a string using scanf() or gets()?

Points to be kept in mind while using scanf():

  • The length of the string entered by the user should not exceed the value declared in the array since C compilers do not show any Array index out of bound error for this. It will simply result in the overwriting of important data.
  • Using scanf() , we can't enter a multi-word string, for example, "New York". This problem can be resolved by using the function gets() and puts() as shown below,

Use of gets() and puts()

Here, puts() can display only one string at a time therefore, two puts() statements are used. Also, unlike printf() , it places the cursor automatically to the next line.

Though gets() can receive only one string at a time, still it is preferable as it can receive multi-word strings .

Author's note:

This was a basic of what strings actually are. In the next article, I will write about string manipulations and standard library string functions . For better understanding, practice these codes on your own by changing the values and outputs. I'm ready to help if the case of queries. Happy coding!

Related Tutorials

  • Standard Library String functions in C language
  • Static functions in C Language
  • The scope of function parameters in C programming language
  • Recursion in C Programming
  • Recursion Tutorial, Example, Advantages and Disadvantages
  • Arrays in C programming language
  • Properties/characteristics of an array
  • C Structure - Definition, Declaration, Access with/without pointer
  • Initialize a struct in accordance with C programming language
  • Size of structure with no members
  • Pointer to structure in C
  • Nested Structure Initialization in C language
  • Nested Structure with Example in C language
  • Size of struct in C | padding, alignment in struct
  • How to copy complete structure in a byte array (character buffer)?
  • C Union - Definition, Declaration, Accessing elements
  • Pointer to Union in C language
  • Pointer Rules in C programming language
  • Pointers Declarations in C programming language
  • C pointer Address operators
  • Accessing the value of a variable using pointer in C
  • Address of (&) and dereference (*) operators with the pointers in C
  • NULL pointer in C
  • Pointers as Argument in C programming language
  • Declaration, Use of Structure Pointers in C programming language
  • Pointer arithmetic in C programming language
  • C pointer to an array
  • Evaluation of statement '*ptr++' in C language
  • Pointer and non-pointer variables declarations together in C?
  • Pointer to an array of integers in C language [Declarations, Initialization with Example]
  • Pointer to Pointer (Double Pointer) in C
  • void pointer as function argument in C
  • Difference between char s[] and char *s declarations in C
  • Copying integer value to character buffer and vice versa in C
  • Difference between Call by Reference and Call by Value | Use of Pointer
  • Typedef function pointer

Comments and Discussions!

Load comments ↻

  • Marketing MCQs
  • Blockchain MCQs
  • Artificial Intelligence MCQs
  • Data Analytics & Visualization MCQs
  • Python MCQs
  • C++ Programs
  • Python Programs
  • Java Programs
  • D.S. Programs
  • Golang Programs
  • C# Programs
  • JavaScript Examples
  • jQuery Examples
  • CSS Examples
  • C++ Tutorial
  • Python Tutorial
  • ML/AI Tutorial
  • MIS Tutorial
  • Software Engineering Tutorial
  • Scala Tutorial
  • Privacy policy
  • Certificates
  • Content Writers of the Month

Copyright © 2024 www.includehelp.com. All rights reserved.

  • Overview of C
  • Features of C
  • Install C Compiler/IDE
  • My First C program
  • Compile and Run C program
  • Understand Compilation Process

C Syntax Rules

  • Keywords and Identifier
  • Understanding Datatypes
  • Using Datatypes (Examples)
  • What are Variables?
  • What are Literals?
  • Constant value Variables - const
  • C Input / Output
  • Operators in C Language
  • Decision Making
  • Switch Statement
  • String and Character array
  • Storage classes

C Functions

  • Introduction to Functions
  • Types of Functions and Recursion
  • Types of Function calls
  • Passing Array to function

C Structures

  • All about Structures
  • Pointers concept
  • Declaring and initializing pointer
  • Pointer to Pointer
  • Pointer to Array
  • Pointer to Structure
  • Pointer Arithmetic
  • Pointer with Functions

C File/Error

  • File Input / Output
  • Error Handling
  • Dynamic memory allocation
  • Command line argument
  • 100+ C Programs with explanation and output

String and Character Array in C

String is a sequence of characters that are treated as a single data item and terminated by a null character '\0' . Remember that the C language does not support strings as a data type. A string is actually a one-dimensional array of characters in C language. These are often used to create meaningful and readable programs.

If you don't know what an array in C means, you can check the C Array tutorial to know about Array in the C language. Before proceeding further, check the following articles:

C Function Calls

C Variables

C Datatypes

For example: The string "home" contains 5 characters including the '\0' character which is automatically added by the compiler at the end of the string.

string in C

Declaring and Initializing String variables in C

Let's see how you can declare and initialize a string variable in C language.

String Input and Output in C

%s format specifier to read a string input from the terminal.

But scanf() function, terminates its input on the first white space it encounters.

edit set conversion code %[..] that can be used to read a line containing a variety of characters, including white spaces.

The gets() function can also be used to read character string with white spaces

Let's see a code example now,

We can also ue gets function to get the string as input.

String Handling Functions in C

C language supports a large number of string handling functions that can be used to carry out many of the string manipulations. These functions are packaged in the string.h library. Hence, you must include string.h header file in your programs to use these functions.

The following are the most commonly used string handling functions.

Method Description
It is used to concatenate(combine) two strings
It is used to show the length of a string
It is used to show the reverse of a string
Copies one string into another
It is used to compare two string

There are many more String functions, but in this tutorial we will learn how to use the above mentioned string functions.

1. strcat() function

strcat() function in C

strcat() will add the string "world" to "hello" i.e ouput = helloworld.

2. strlen() and strcmp() function

strlen() will return the length of the string passed to it and strcmp() will return the ASCII difference between first unmatching character of two strings.

3. strcpy() function

It copies the second string argument to the first string argument.

srtcpy() function in C

let's see an example of strcpy() function,

StudyTonight

4. strrev() function:

It is used to reverse the given string expression.

strrev() function in C

Code snippet for strrev() :

Enter your string: studytonight Your reverse string is: thginotyduts

Related Tutorials:

  • ← Prev
  • Next →

home

  • What is C Language
  • History of C
  • Features of C
  • How to install C
  • First C Program
  • Compilation Process in C
  • printf scanf
  • Variables in C
  • Data Types in c
  • Keywords in c
  • C Identifiers
  • C Operators
  • C Format Specifier
  • C Escape Sequence
  • ASCII value in C
  • Constants in C
  • Literals in C
  • Tokens in C
  • Static in C
  • Programming Errors in C
  • Compile time vs Runtime
  • Conditional Operator in C
  • Bitwise Operator in C
  • 2s complement in C

C Fundamental Test

C control statements.

  • if-else vs switch
  • C do-while loop
  • C while loop
  • Nested Loops in C
  • Infinite Loop in C
  • Type Casting
  • C Control Statement Test

C Functions

  • What is function
  • Call: Value & Reference
  • Recursion in c
  • Storage Classes
  • C Functions Test
  • Return an Array in C
  • Array to Function

C Array Test

  • C Pointer to Pointer
  • C Pointer Arithmetic
  • Dangling Pointers in C
  • sizeof() operator in C
  • const Pointer in C
  • void pointer in C
  • C Dereference Pointer
  • Null Pointer in C
  • C Function Pointer
  • Function pointer as argument in C

C Pointers Test

C dynamic memory.

  • Dynamic memory
  • String in C
  • C gets() & puts()
  • C String Functions

C String Test

  • C Math Functions

C Structure Union

  • C Structure
  • typedef in C
  • C Array of Structures
  • C Nested Structure
  • Structure Padding in C

C Structure Test

  • C File Handling
  • C fprintf() fscanf()
  • C fputc() fgetc()
  • C fputs() fgets()
  • C Preprocessor

C Preprocessor Test

C command line.

  • Command Line Arguments
  • C Expressions
  • Data Segments
  • Flow of C Program
  • Classification of Programming Languages
  • What is getch() in C
  • What is the function call in C
  • typedef vs define in C
  • C Programming Test
  • Top 10+ C Programs
  • Fibonacci Series
  • Prime Number
  • Palindrome Number
  • C program to compare the two strings
  • Strings Concatenation in C
  • Armstrong Number
  • Sum of digits
  • Count the number of digits in C
  • Reverse Number
  • Swap Number
  • Print "Hello" without ;
  • Assembly code in C
  • C program without main
  • Matrix Multiplication
  • Decimal to Binary
  • Number in Characters
  • Alphabet Triangle
  • Number Triangle
  • Fibonacci Triangle
  • Hexadecimal to Binary
  • Hexadecimal to Decimal
  • Octal to Hexadecimal in C
  • Strong number in C
  • Star Program in C
  • itoa Function in C
  • Extra Long Factorials in C
  • Leap year program in C
  • Perfect Number Program in C
  • Variables vs Constants
  • Round Robin Program in C with Output
  • C Program to find the roots of quadratic equation
  • Type Casting vs Type Conversion
  • How to run a C program in Visual Studio Code
  • Modulus Operator in C/C++
  • Sum of first N natural numbers in C
  • Big O Notation in C
  • LCM of two numbers in C
  • while loop vs do-while loop in C
  • Memory Layout in C
  • Balanced Parenthesis in C
  • Binary to Decimal Number in C
  • GCD of two numbers in C
  • Getchar() function in C
  • flowchart in C
  • Simpson Method
  • Pyramid Patterns in C
  • Random Function in C
  • Floyd's Triangle in C
  • C Header Files
  • abs() function in C
  • Atoi() function in C
  • Structure Pointer in C
  • sprintf() in C
  • Range of Int in C
  • C Program to convert 24 Hour time to 12 Hour time
  • What is double in C
  • What is the main in C
  • Calculator Program in C
  • Calloc in C
  • user-defined vs library function in C
  • ASCII Table in C
  • Static function in C
  • Reverse a String in C
  • Twin Prime Numbers in C
  • strchr() function in C
  • Structure of a C program
  • Power Function in C
  • Malloc in C
  • Table Program in C
  • Types of Recursion in C
  • Convert Uppercase to Lowercase in C
  • Unary Operator in C
  • Arithmetic Operator in C
  • Ceil Function in C
  • Relational Operator in C
  • Assignment Operator in C
  • Pre-increment and Post-increment Operator in C
  • Pointer vs array in C
  • Restrict keyword in C
  • The exit() function in C
  • Const Qualifier in C
  • Sequence Points in C
  • Anagram in C
  • Increment and Decrement Operators in C
  • Logical AND Operator in C
  • Shift Operators in C
  • Near, Far, and Huge pointers in C language
  • Magic Number in C
  • Remove Duplicate Elements from an Array in C
  • Generic Linked list in C
  • isalnum() function in C
  • isalpha() function in C
  • Bisection Method in C
  • snprintf() function in C
  • Remove an element from an array in C
  • Square Root in C
  • isprint() function in C
  • isdigit() function in C
  • isgraph() function in C
  • Logical NOT (!) Operator in C
  • Self-referential structure
  • Break Vs. Continue in C
  • For vs. While loop in C
  • Abort() Function in C
  • Assert in C
  • Floor() Function in C
  • memcmp() in C
  • Find Day from Day in C without Using Function
  • Find Median of 1D Array Using Functions in C
  • Find Reverse of an Array in C Using Functions
  • Find Occurrence of Substring in C using Function
  • Find out Power without Using POW Function in C
  • Exponential() in C
  • islower() in C
  • memcpy() in C
  • memmove() in C
  • Matrix Calculator in C
  • Bank Account Management System
  • Library Management System in C
  • 8th Sep - Calendar Application in C
  • 8th Sep - va_start() in C programming
  • 8th Sep - Ascii vs Unicode
  • Student Record System in C
  • Contact Management System in C
  • Cricket Score Sheet in C
  • C/C++ Tricky Programs
  • Clearing the Input Buffer in C/C++
  • In-place Conversion of Sorted DLL to Balanced BST
  • Merge Two Balanced Binary Search Trees
  • Responsive Images in Bootstrap with Examples
  • Why can't a Priority Queue Wrap around like an Ordinary Queue
  • Customer Billing System in C
  • Builtin functions of GCC compiler
  • Integer Promotions in C
  • Bit Fields in C
  • Department Management System in C
  • Local Labels in C
  • School Billing System in C
  • Banking Account System in C using File handling
  • Data Structures and Algorithms in C - Set 1
  • Data Structures and Algorithms in C - Set 2
  • Employee Record System in C
  • Hangman Game in C
  • Hospital Management System in C
  • Number of even and odd numbers in a given range
  • qsort() in C
  • Quiz game in C
  • An Array of Strings in C
  • Peak element in the Array in C
  • Move all negative elements to one side of an Array-C
  • Reverse an Array in C
  • 3 way merge sort in c
  • Segregate 0s and 1s in an array
  • Articulation Points and Bridges
  • Execution of printf with ++ Operators
  • Understanding the extern Keyword in C
  • Banker's Algorithm in C
  • FIFO Page Replacement Algorithm in C
  • Kruskal's Algorithm in C
  • FCFS Program in C
  • Triple DES Algorithm in C
  • Window Sliding Technique in C
  • Sleeping Barber Problem Solution in C
  • How to Add Matrix in C
  • C Program to Demonstrate fork() and pipe()
  • Deadlock Prevention using Banker's Algorithm in C
  • Simple Stopwatch Program in C
  • Add Node to Linked List in C
  • How to Add two Array in C
  • Algorithm in C language
  • Add Digits of Number in C
  • Add Element in Array in C
  • Add String in C
  • Add Two Matrices in C
  • Add two numbers using Pointer in C
  • Order of Complexity in C
  • Pattern Matching Algorithm in C
  • Adaline Program in C
  • Adam Number in C Program
  • Adam Number or not in C Program
  • Add 2 Matrix in C
  • Add 2 Strings in C
  • Add a Character to a String in C
  • Best Compiler for C Programming
  • C Program to Convert Infix to Postfix
  • C Program For Printing Inverted Pyramid
  • Control String in C Language
  • How to Find Time Complexity of a Program in C
  • Top C Projects in 2023
  • Convert a Char Array into a Double in C
  • Conio.h in C
  • Decision-Making Statements in C
  • What is Hashing in C
  • Bubble sort program in C
  • Comma Operator in C
  • Control Statements in C
  • ctype.h in C
  • First Fit Algorithm in C
  • Hello World Program in C
  • Logical operator in c
  • Memory leak in C
  • Null character in C
  • Operator precedence in C
  • Putchar() function in C
  • Quick Sort in C
  • realloc in C
  • Special operator in C
  • Volatile Keyword in C
  • CRC program in C
  • Binary search algorithm in C
  • Kruskal algorithm in C
  • Transpose of Matrix in C
  • Actual and Formal Parameters in C
  • Bit Stuffing in C
  • Difference between C and Embedded C
  • Dynamic Array in C
  • Jump statement in C
  • Multidimensional array in C
  • Priority scheduling program in C
  • Pseudo code in C
  • Data Structure in C
  • Difference between switch statement and if-else-if ladder statement in C
  • BFS Program in C
  • Nested if else statement in C
  • Pattern Programs in C
  • SJF Scheduling program in C
  • Stdlib.h in C
  • User defined function in C
  • How to use Pointers in C language
  • What is a Storage Class in C
  • What is short int in C
  • Insertion Sort in C
  • Segmentation Fault in C
  • FUNCTION PROTOTYPE IN C
  • Iteration in C
  • One dimensional array in C
  • Overview of Structures and Unions in C
  • Difference between 1D and 2D array in C
  • Differences between Float and Double in C
  • Fizz Buzz Program in C
  • Formatted and Unformatted Input Output in C
  • Garbage collection in C
  • Library function in C
  • Strtok() function in C
  • Symbolic Constants in C
  • What is Garbage Value in C
  • What is size_t in C
  • What is the use of "\r" in C
  • Address operator in C
  • BOOTHS Algorithm in C
  • Character stuffing program in C
  • Difference between printf() and scanf() in C
  • Global Variable in C
  • Lexical Analyzer in C
  • Pascal Triangle in C
  • Postfix Evaluation in C
  • Strncmp() function in C
  • Type Qualifiers in C
  • Unsigned int in C
  • What is Perror in C
  • Difference Between Array and String in C
  • Execvp() Function in C
  • Explain Recursion with Example in C
  • Contiguous file allocation program in C
  • ENTRY CONTROL LOOP IN C
  • EXIT CONTROL LOOP IN C
  • Fopen() function in C
  • Hollow Diamond Pattern in C
  • Register Keyword in C
  • Strcmpi() function in C
  • Strtol() function in C
  • System function in C
  • Difference between parameter and arguments in C
  • Execlp() function in C
  • Fabs() function in C
  • Recursive Descent Parser Program in C
  • Difference Between exit() and return() in C
  • Skill rack solution in C
  • Stack overflow in C
  • Static_cast in C
  • Stdin and Stdout in C
  • Strrchr() function in C
  • Strsep() function in C
  • Strcspn() function in C
  • Strtoul() Function in C
  • Area of Circle program in C
  • Branching statements in C
  • Bubble Sort in C
  • C program to adding of two binary numbers
  • C program to Search an Element in an Array
  • Difference between Object code and Source code
  • Electricity bill program in C
  • RSA algorithm in C
  • Singly linked list in C
  • Strftime() in C
  • Strlen() function in C
  • Swap first and last digit of a number in C
  • Addition program in C
  • clrscr in C
  • Distance Vector Routing Program in C
  • Even odd programs in C
  • How to Access Structure Members in C
  • How to Change C Users Username in Windows 10
  • Linear search in C
  • Symmetric Matrix in C
  • fgets() function in C
  • Length of array in C
  • MULTITHREADING IN C
  • Number pattern program in C
  • Strcpy() function in C
  • Best Books for C Programming
  • C Program to Calculate Area and Circumference of Circle
  • Character Set in C
  • Array Rotation in C
  • Random Access File in C
  • atan2() Function in C
  • Digital Clock in C Programming
  • How Many IP Addresses have a class c Network
  • How Many Tokens in C
  • Linked error in C
  • Lvalue and Rvalue in C
  • Auto and Static Variable in C
  • feof() function in C
  • Gauss Jordan Method in C
  • Gauss Seidel Method in C
  • Getw() and Putw() function in C
  • lseek() in C
  • usleep() function in C
  • First and Follow Program in C
  • Interpolation Search in C
  • strdup() function in C
  • Generic Keyword in C
  • getopt() function in C
  • getpid() and getppid() function in C
  • Magic Square Function in C
  • Reentrant Function in C
  • Return Statement in C
  • Travelling Salesman Problem in C
  • Double Float in C
  • fseek() vs rewind() in C
  • How to create your own header files in C
  • Implicit type conversion in C
  • Inter Function Communication in C
  • kbhit() in C
  • Multiline Macros in C
  • Scanset in C
  • Tail Recursion in C
  • C program for currency denomination
  • C program for secant method
  • Fread() Function in C
  • Hangman game program in C
  • Hilbert curve program in C
  • Newton Forward Interpolation in C
  • Tower of Hanoi
  • Vigenere Cypher Program in C
  • C language MCQ
  • C language MCQ Part 2
  • Prime Numbers List
  • Composite Numbers List
  • Square Numbers List
  • Binary Numbers List
  • Fibonacci Numbers List
  • Ounces in a Cup
  • Ounces in a Pound
  • Ounces in a Gallon
  • Ounces in a Liter
  • Ounces in a Pint
  • Ounces in a Quart
  • Ounces in a Tablespoon

C Interview

  • C Interview Questions
  • C Fundamental 1
  • C Fundamental 2
  • C Fundamental 3
  • C Fundamental 4

C Control Test

  • C Control Statement 1
  • C Control Statement 2
  • C Control Statement 3
  • C Control Statement 4

C Function Test

  • C Functions 1
  • C Functions 2
  • C Functions 3
  • C Functions 4
  • C Pointers 1
  • C Pointers 2
  • C Pointers 3
  • C Pointers 4
  • C Structure 1
  • C Structure 2
  • C Structure 3
  • C Structure 4
  • C Preprocessor 1
  • C Preprocessor 2
  • C Preprocessor 3
  • C Preprocessor 4

The string can be defined as the one-dimensional array of characters terminated by a null ('\0'). The character array or the string is used to manipulate text such as word or sentences. Each character in the array occupies one byte of memory, and the last character must always be 0. The termination character ('\0') is important in a string since it is the only way to identify where the string ends. When we define a string as char s[10], the character s[10] is implicitly initialized with the null in the memory.

There are two ways to declare a string in c language.

Let's see the example of declaring in C language.

As we know, array index starts from 0, so it will be represented as in the figure given below.

We can also define the in C language. For example:

In such case, '\0' will be appended at the end of the string by the compiler.

There are two main differences between char array and literal.

Let's see a simple example where a string is declared and being printed. The '%s' is used as a format specifier for the string in c language.

Traversing the string is one of the most important aspects in any of the programming languages. We may need to manipulate a very large text which can be done by traversing the text. Traversing string is somewhat different from the traversing an integer array. We need to know the length of the array to traverse an integer array, whereas we may use the null character in the case of string to identify the end the string and terminate the loop.

Hence, there are two ways to traverse a string.

Let's discuss each one of them.

Let's see an example of counting the number of vowels in a string.

Let's see the same example of counting the number of vowels by using the null character.

Till now, we have used scanf to accept the input from the user. However, it can also be used in the case of strings but with a different scenario. Consider the below code which stores the string while space is encountered.

It is clear from the output that, the above code will not work for space separated strings. To make this code working for the space separated strings, the minor changed required in the scanf function, i.e., instead of writing scanf("%s",s), we must write: scanf("%[^\n]s",s) which instructs the compiler to store the string s while the new line (\n) is encountered. Let's consider the following example to store the space-separated strings.

Here we must also notice that we do not need to use address of (&) operator in scanf to store a string since string s is an array of characters and the name of the array, i.e., s indicates the base address of the string (character array) therefore we need not use & with it.

However, there are the following points which must be noticed while entering the strings by using scanf.

We have used pointers with the array, functions, and primitive data types so far. However, pointers can be used to point to the strings. There are various advantages of using pointers to point strings. Let us consider the following example to access the string via the pointer.

Once a string is defined, it cannot be reassigned to another set of characters. However, using pointers, we can assign the set of characters to the string. Consider the following example.



Latest Courses

Python

We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks

Contact info

G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India

[email protected] .

Facebook

Interview Questions

Online compiler.

  • C Data Types
  • C Operators
  • C Input and Output
  • C Control Flow
  • C Functions
  • C Preprocessors
  • C File Handling
  • C Cheatsheet
  • C Interview Questions

C Exercises – Practice Questions with Solutions for C Programming

The best way to learn C programming language is by hands-on practice. This C Exercise page contains the top 30 C exercise questions with solutions that are designed for both beginners and advanced programmers. It covers all major concepts like arrays, pointers, for-loop, and many more.

C-Exercises

So, Keep it Up! Solve topic-wise C exercise questions to strengthen your weak topics.

C Programming Exercises

The following are the top 30 programming exercises with solutions to help you practice online and improve your coding efficiency in the C language. You can solve these questions online in GeeksforGeeks IDE.

Q1: Write a Program to Print “Hello World!” on the Console.

In this problem, you have to write a simple program that prints “Hello World!” on the console screen.

For Example,

Click here to view the solution.

Q2: write a program to find the sum of two numbers entered by the user..

In this problem, you have to write a program that adds two numbers and prints their sum on the console screen.

Q3: Write a Program to find the size of int, float, double, and char.

In this problem, you have to write a program to print the size of the variable.

Q4: Write a Program to Swap the values of two variables.

In this problem, you have to write a program that swaps the values of two variables that are entered by the user.

Swap-two-Numbers

Swap two numbers

Q5: Write a Program to calculate Compound Interest.

In this problem, you have to write a program that takes principal, time, and rate as user input and calculates the compound interest.

Q6: Write a Program to check if the given number is Even or Odd.

In this problem, you have to write a program to check whether the given number is even or odd.

Q7: Write a Program to find the largest number among three numbers.

In this problem, you have to write a program to take three numbers from the user as input and print the largest number among them.

Q8: Write a Program to make a simple calculator.

In this problem, you have to write a program to make a simple calculator that accepts two operands and an operator to perform the calculation and prints the result.

Q9: Write a Program to find the factorial of a given number.

In this problem, you have to write a program to calculate the factorial (product of all the natural numbers less than or equal to the given number n) of a number entered by the user.

Q10: Write a Program to Convert Binary to Decimal.

In this problem, you have to write a program to convert the given binary number entered by the user into an equivalent decimal number.

Q11: Write a Program to print the Fibonacci series using recursion.

In this problem, you have to write a program to print the Fibonacci series(the sequence where each number is the sum of the previous two numbers of the sequence) till the number entered by the user using recursion.

FIBONACCI-SERIES

Fibonacci Series

Q12: Write a Program to Calculate the Sum of Natural Numbers using recursion.

In this problem, you have to write a program to calculate the sum of natural numbers up to a given number n.

Q13: Write a Program to find the maximum and minimum of an Array.

In this problem, you have to write a program to find the maximum and the minimum element of the array of size N given by the user.

Q14: Write a Program to Reverse an Array.

In this problem, you have to write a program to reverse an array of size n entered by the user. Reversing an array means changing the order of elements so that the first element becomes the last element and the second element becomes the second last element and so on.

reverseArray

Reverse an array

Q15: Write a Program to rotate the array to the left.

In this problem, you have to write a program that takes an array arr[] of size N from the user and rotates the array to the left (counter-clockwise direction) by D steps, where D is a positive integer. 

Q16: Write a Program to remove duplicates from the Sorted array.

In this problem, you have to write a program that takes a sorted array arr[] of size N from the user and removes the duplicate elements from the array.

Q17: Write a Program to search elements in an array (using Binary Search).

In this problem, you have to write a program that takes an array arr[] of size N and a target value to be searched by the user. Search the target value using binary search if the target value is found print its index else print ‘element is not present in array ‘.

Q18: Write a Program to reverse a linked list.

In this problem, you have to write a program that takes a pointer to the head node of a linked list, you have to reverse the linked list and print the reversed linked list.

Q18: Write a Program to create a dynamic array in C.

In this problem, you have to write a program to create an array of size n dynamically then take n elements of an array one by one by the user. Print the array elements.

Q19: Write a Program to find the Transpose of a Matrix.

In this problem, you have to write a program to find the transpose of a matrix for a given matrix A with dimensions m x n and print the transposed matrix. The transpose of a matrix is formed by interchanging its rows with columns.

Q20: Write a Program to concatenate two strings.

In this problem, you have to write a program to read two strings str1 and str2 entered by the user and concatenate these two strings. Print the concatenated string.

Q21: Write a Program to check if the given string is a palindrome string or not.

In this problem, you have to write a program to read a string str entered by the user and check whether the string is palindrome or not. If the str is palindrome print ‘str is a palindrome’ else print ‘str is not a palindrome’. A string is said to be palindrome if the reverse of the string is the same as the string.

Q22: Write a program to print the first letter of each word.

In this problem, you have to write a simple program to read a string str entered by the user and print the first letter of each word in a string.

Q23: Write a program to reverse a string using recursion

In this problem, you have to write a program to read a string str entered by the user, and reverse that string means changing the order of characters in the string so that the last character becomes the first character of the string using recursion. 

Reverse-a-String

reverse a string

Q24: Write a program to Print Half half-pyramid pattern.

In this problem, you have to write a simple program to read the number of rows (n) entered by the user and print the half-pyramid pattern of numbers. Half pyramid pattern looks like a right-angle triangle of numbers having a hypotenuse on the right side.

Q25: Write a program to print Pascal’s triangle pattern.

In this problem, you have to write a simple program to read the number of rows (n) entered by the user and print Pascal’s triangle pattern. Pascal’s Triangle is a pattern in which the first row has a single number 1 all rows begin and end with the number 1. The numbers in between are obtained by adding the two numbers directly above them in the previous row.

pascal-triangle

Pascal’s Triangle

Q26: Write a program to sort an array using Insertion Sort.

In this problem, you have to write a program that takes an array arr[] of size N from the user and sorts the array elements in ascending or descending order using insertion sort.

Q27: Write a program to sort an array using Quick Sort.

In this problem, you have to write a program that takes an array arr[] of size N from the user and sorts the array elements in ascending order using quick sort.

Q28: Write a program to sort an array of strings.

In this problem, you have to write a program that reads an array of strings in which all characters are of the same case entered by the user and sort them alphabetically. 

Q29: Write a program to copy the contents of one file to another file.

In this problem, you have to write a program that takes user input to enter the filenames for reading and writing. Read the contents of one file and copy the content to another file. If the file specified for reading does not exist or cannot be opened, display an error message “Cannot open file: file_name” and terminate the program else print “Content copied to file_name”

Q30: Write a program to store information on students using structure.

In this problem, you have to write a program that stores information about students using structure. The program should create various structures, each representing a student’s record. Initialize the records with sample data having data members’ Names, Roll Numbers, Ages, and Total Marks. Print the information for each student.

We hope after completing these C exercises you have gained a better understanding of C concepts. Learning C language is made easier with this exercise sheet as it helps you practice all major C concepts. Solving these C exercise questions will take you a step closer to becoming a C programmer.

Frequently Asked Questions (FAQs)

Q1. what are some common mistakes to avoid while doing c programming exercises.

Some of the most common mistakes made by beginners doing C programming exercises can include missing semicolons, bad logic loops, uninitialized pointers, and forgotten memory frees etc.

Q2. What are the best practices for beginners starting with C programming exercises?

Best practices for beginners starting with C programming exercises: Start with easy codes Practice consistently Be creative Think before you code Learn from mistakes Repeat!

Q3. How do I debug common errors in C programming exercises?

You can use the following methods to debug a code in C programming exercises Read the error message carefully Read code line by line Try isolating the error code Look for Missing elements, loops, pointers, etc Check error online

Please Login to comment...

Similar reads.

  • Best External Hard Drives for Mac in 2024: Top Picks for MacBook Pro, MacBook Air & More
  • How to Watch NFL Games Live Streams Free
  • OpenAI o1 AI Model Launched: Explore o1-Preview, o1-Mini, Pricing & Comparison
  • How to Merge Cells in Google Sheets: Step by Step Guide
  • #geekstreak2024 – 21 Days POTD Challenge Powered By Deutsche Bank

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Char String Assignment

I am working on Microsoft Visual Studio environment. I came across a strange behavior

The result is:

That means the des[0] is not being initialized. As src is pointing to the first element of the string. I guess by rules this should work.

  • variable-assignment

Vinay's user avatar

  • 1 Please tag the question with the language, so people know what you are talking about. –  Oded Commented Dec 27, 2011 at 13:46
  • If you're using C++, why in the world are you using printf and C-style strings? –  Cody Gray ♦ Commented Dec 27, 2011 at 13:50
  • @CodyGray: Sorry. I am using C language as platform. I have edited the tag. –  Vinay Commented Dec 27, 2011 at 14:02

5 Answers 5

This is undefined behavior:

Try this instead:

cnicutar's user avatar

  • Thank you. yes, it does work. But isn't it in both the cases, des would be pointing to the same location. And eventually 'des[0]' is equivalent to '*(des+0)'. by undefined behavior, are you referring to the C specifications? –  Vinay Commented Dec 27, 2011 at 13:54
  • @vinaygarg It's not the same thing. Yes, I am talking about the C standard, but I expect the C++ standards to be similar in this respect. –  cnicutar Commented Dec 27, 2011 at 13:55

Since src and des are initialized with string literals, their type should actually be const char * , not char * ; like this:

There was never memory allocated for either of them, they just point to the predefined constants. Therefore, the statement des[0] = src[0] is undefined behavior; you're trying to change a constant there!

Any decent compiler should actually warn you about the implicit conversion from const char * to char * ...

If using C++, consider using std::string instead of char * , and std::cout instead of printf .

codeling's user avatar

Section 2.13.4 of ISO/IEC 14882 (Programming languages - C++) says:

A string literal is a sequence of characters (as defined in 2.13.2) surrounded by double quotes, optionally beginning with the letter L, as in "..." or L"...". A string literal that does not begin with L is an ordinary string literal, also referred to as a narrow string literal. An ordinary string literal has type “array of n const char” and static storage duration (3.7), where n is the size of the string as defined below, and is initialized with the given characters. ...

Whether all string literals are distinct (that is, are stored in nonoverlapping objects) is implementation defined. The effect of attempting to modify a string literal is undefined .

kev's user avatar

In C, string literals such as "123" are stored as arrays of char ( const char in C++). These arrays are stored in memory such that they are available over the lifetime of the program. Attempting to modify the contents of a string literal results in undefined behavior; sometimes it will "work", sometimes it won't, depending on the compiler and the platform, so it's best to treat string literals as unwritable.

Remember that under most circumstances, an expression of type "N-element array of T " will be converted to an expression of type "pointer to T " whose value is the location of the first element in the array.

Thus, when you write

the expressions "123" and "abc" are converted from "3-element array of char " to "pointer to char ", and src will point to the '1' in "123" , and des will point to the 'a' in "abc" .

Again, attempting to modify the contents of a string literal results in undefined behavior, so when you write

the compiler is free to treat that statement any way it wants to, from ignoring it completely to doing exactly what you expect it to do to anything in between. That means that string literals, or a pointer to them, cannot be used as target parameters to calls like strcpy , strcat , memcpy , etc., nor should they be used as parameters to calls like strtok .

John Bode's user avatar

vinaygarg : That means the des[0] is not being initialized. As src is pointing to the first element of the string. I guess by rules this should work.

Firstly you must remember that *src and *dst are defined as pointers, nothing more, nothing less.

So you must then ask yourself what exactly "123" and "abc" are and why it cannot be altered? Well to cut a long story short, it is stored in application memory, which is read-only . Why? The strings must be stored with the program in order to be available to your code at run time, in theory you should get a compiler warning for assigning a non-const char* to a const char * . Why is it read-only ? The memory for exe's and dll's need to be protected from being overwritten somehow, so it must be read-only to stop bugs and viruses from modifying executing code.

So how can you get this string into modifiable memory?

Keldon Alleyne's user avatar

  • @pmg My apologies, was not aware of C-only requirement at time of writing. Updated, thanks for pointing that out. –  Keldon Alleyne Commented Dec 27, 2011 at 14:09

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged c variable-assignment or ask your own question .

  • The Overflow Blog
  • Looking under the hood at the tech stack that powers multimodal AI
  • Featured on Meta
  • User activation: Learnings and opportunities
  • Preventing unauthorized automated access to the network
  • What does a new user need in a homepage experience on Stack Overflow?
  • Announcing the new Staging Ground Reviewer Stats Widget

Hot Network Questions

  • My one-liner 'delete old files' command finds the right files but will not delete them
  • Is it possible to make sand from bones ? Would it have the same properties as regular sand?
  • Sent money to rent an apartment, landlord delaying refund with excuses. Is this a scam?
  • Model looks dented but geometry is correct
  • Why are Jesus and Satan both referred to as the morning star?
  • Was the total glaciation of the world, a.k.a. snowball earth, due to Bok space clouds?
  • How to react to a rejection based on a single one-line negative review?
  • Book about supernatural beings running stores in a mall
  • Is there a "hard problem of aesthetics?"
  • How can I add cache information to InboundPathProcessor?
  • How to translate the letter Q to Japanese?
  • Establishing Chirality For a 4D Person?
  • Why believe in the existence of large cardinals rather than just their consistency?
  • In The Martian, what does Mitch mean when he is talking to Teddy and says that the space program is not bigger than one person?
  • Enter a personal identification number
  • A continuous analogue of the notion of Hilbert basis
  • Writing in first person for fiction novel, how to portray her inner dialogue and drag it out to make a chapter long enough?
  • Parameters of the sampling distribution of the sample proportion
  • What is the meaning of a sentence from Agatha Christie (*Murder of Roger Ackroyd*)?
  • Can a 20A circuit mix 15A and 20A receptacles, when a 20A is intended for occassional space heater use?
  • Smallest prime q such that concatenation (p+q)"q is a prime
  • Big bang and the horizon problem
  • 〈ü〉 vs 〈ue〉 in German, particularly names
  • Superuser and Sudo not working on Debian 12

c language string assignment

IMAGES

  1. C# : String assignment in C#

    c language string assignment

  2. Top String Assignment Questions in C Programming

    c language string assignment

  3. String in C

    c language string assignment

  4. C Strings (with Examples)

    c language string assignment

  5. Array of Strings in C

    c language string assignment

  6. C Language

    c language string assignment

VIDEO

  1. String

  2. Assignment Operator in C Programming

  3. C-string functions: strlen, strcpy, strcat, strncpy, strncat, strcmp, strstr

  4. String

  5. Assignment Operator in C Programming

  6. Strings in C Programming (Hindi/Urdu)

COMMENTS

  1. c

    person p = {"John", "Doe",30}; works in the first example. You cannot assign (in the conventional sense) a string in C. The string literals you have ("John") are loaded into memory when your code executes. When you initialize an array with one of these literals, then the string is copied into a new memory location.

  2. String assignment in C

    char str[] = "string"; is a declaration, in which you're allowed to give the string an initial value. name[10] identifies a single char within the string, so you can assign a single char to it, but not a string. There's no simple assignment for C-style strings outside of the declaration. You need to use strcpy for that.

  3. Strings in C

    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.

  4. Strings in C (With Examples)

    C Programming Strings. In C programming, a string is a sequence of characters terminated with a null character \0. For example: char c[] = "c string"; When the compiler encounters a sequence of characters enclosed in the double quotation marks, it appends a null character \0 at the end by default. Memory Diagram.

  5. C String

    The length of strings in C. The length of a string in C is just the number of characters in a word, without including the string terminator (despite it always being used to terminate strings). The string terminator is not accounted for when you want to find the length of a string. For example, the string freeCodeCamp has a length of 12 characters.

  6. Strings in C with Examples: String Functions

    String Functions in C. In C programming language, several string functions can be used to manipulate strings. To use them, you must include the <string.h> header file in your program. Here are some of the commonly used string functions in C: strlen(): This function is used to find the length of a string.

  7. C String Functions

    5. strchr() The strchr() function in C is a predefined function used for string handling. This function is used to find the first occurrence of a character in a string. Syntax. char *strchr(const char *str, int c); Parameters. str: specifies the pointer to the null-terminated string to be searched in. ch: specifies the character to be searched for. Here, str is the string and ch is the ...

  8. Assignment Expressions (GNU C Language Manual)

    7 Assignment Expressions. As a general concept in programming, an assignment is a construct that stores a new value into a place where values can be stored—for instance, in a variable. Such places are called lvalues (see Lvalues) because they are locations that hold a value. An assignment in C is an expression because it has a value; we call it an assignment expression.

  9. C Strings

    Strings are used for storing text/characters. For example, "Hello World" is a string of characters. Unlike many other programming languages, C does not have a String type to easily create string variables. Instead, you must use the char type and create an array of characters to make a string in C: char greetings [] = "Hello World!";

  10. C

    C String function - Strrchr char *strrchr(char *str, int ch) It is similar to the function strchr, the only difference is that it searches the string in reverse order, now you would have understood why we have extra r in strrchr, yes you guessed it correct, it is for reverse only.

  11. Strings in C: How to Declare & Initialize a String Variables in C

    Hence, to display a String in C, you need to make use of a character array. The general syntax for declaring a variable as a String in C is as follows, char string_variable_name [array_size]; The classic Declaration of strings can be done as follow: char string_name[string_length] = "string"; The size of an array must be defined while declaring ...

  12. String Manipulations In C Programming Using Library Functions

    Most, if not all, of the time string manipulation can be done manually but, this makes programming complex and large. To solve this, C supports a large number of string handling functions in the standard library "string.h". Few commonly used string handling functions are discussed below:

  13. Assignment Operators in C

    1. "=": This is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left. Example: a = 10;b = 20;ch = 'y'; 2. "+=": This operator is combination of '+' and '=' operators. This operator first adds the current value of the variable on left to the value on the right and ...

  14. Strings in C Programming Language (With Examples)

    Strings in C programming language: In this tutorial, we will learn about the strings in C, declaring, initializing, printing getting the length of the string, and many more with the help of examples. ... You cannot directly assign a string by using the assignment (=) operator. You can initialize a string anywhere in the program after the ...

  15. Strings In C

    There are 4 ways in which we can initialize string in C language. These are by-1. Assigning a string literal with size 2. Assigning a string literal without size ... This is the most common way to initialize strings in C, as it allows for the direct assignment of array size and value at once. The syntax used for this method is given below ...

  16. String and Character Arrays in C Language

    String is a sequence of characters that are treated as a single data item and terminated by a null character '\0'.Remember that the C language does not support strings as a data type. A string is actually a one-dimensional array of characters in C language. These are often used to create meaningful and readable programs. If you don't know what an array in C means, you can check the C Array ...

  17. How do you assign a string in C

    char initials[8]; and fill that memory zone to become a proper string: initials[0] = fn[0]; initials[1] = ln[0]; initials[2] = (char)0; the last assignment (to initials[2]) is putting the NUL terminating byte and makes that initials buffer a proper string. Then you could output it using printf or fputs.

  18. C Strings (with Examples)

    C Strings. The string can be defined as the one-dimensional array of characters terminated by a null ('\0'). The character array or the string is used to manipulate text such as word or sentences. Each character in the array occupies one byte of memory, and the last character must always be 0. The termination character ('\0') is important in a ...

  19. Assign one struct to another in C

    4. Yes, you can assign one instance of a struct to another using a simple assignment statement. In the case of non-pointer or non pointer containing struct members, assignment means copy. In the case of pointer struct members, assignment means pointer will point to the same address of the other pointer.

  20. C Exercises

    C is a procedural programming language. It was initially developed by Dennis Ritchie in the year 1972. It was mainly developed as a system programming language to write an operating system. The main features of C language include low-level access to memory, a simple set of keywords, and a clean style, these features make C language suitable for sys

  21. c

    A string literal that does not begin with L is an ordinary string literal, also referred to as a narrow string literal. An ordinary string literal has type "array of n const char" and static storage duration (3.7), where n is the size of the string as defined below, and is initialized with the given characters. ...