• 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

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 a string variables:

String input and output:.

%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

String Handling Functions:

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.

strcat() function in C:

strcat() function in C

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

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.

strcpy() function:

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

srtcpy() function in C

Example of strcpy() function:

StudyTonight

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 →
  • Array of Strings in C

Use 2D Array Notation to Declare Array of Strings in C

Use the char* array notation to declare array of strings in c.

Array of Strings in C

This article will demonstrate multiple methods about how to declare an array of strings in C.

Strings in C are simply a sequence of chars stored in a contiguous memory region. One distinction about character strings is that there is a terminating null byte \0 stored at the end of the sequence, denoting one string’s end. If we declare a fixed array of char using the [] notation, then we can store a string consisting of the same number of characters in that location.

Note that one extra character space for the terminating null byte should be considered when copying the character string to the array location. Thus, one can declare a two-dimensional char array with brackets notation and utilize it as the array of strings.

The second dimension of the array will limit the maximum length of the string. In this case, we arbitrarily define a macro constant - MAX_LENGTH equal to 100 characters.

The whole array can be initialized with {""} notation, which zeros out each char element in the array.

When storing the string values in the already initialized array, the assignment operator is not permitted, and special memory copying functions should be employed like strcpy .

Alternatively, we can initialize the two-dimensional char array instantly when declared. The modern C11 standard allows to initialize char arrays with string literals and even store null byte at the end of the string automatically when the array length is larger than the string itself.

Initializer list notation is similar to the C++ syntax. Each curly braced element is supposed to be stored in a consecutive memory region of length MAX_LENGTH . In case the initializer notation specifies the fewer elements than the array size, the remaining elements are implicitly initialized with \0 bytes.

char* is the type that is generally used to store character strings. Declaring the array of char* gives us the fixed number of pointers pointing to the same number of character strings. It can be initialized with string literals as shown in the following example, assigned to or copied using special functions provided in the header string.h .

As an alternative, one can specify the {} braces only, which will initialize the pointers in the array to null , and they can be later used to stored other string addresses, or the programmer can even allocate dynamic memory.

Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

Related Article - C Array

  • How to Copy Char Array in C
  • How to Dynamically Allocate an Array in C
  • How to Clear Char Array in C
  • How to Initialize Char Array in C
  • How to Print Char Array in C

Related Article - C String

  • Null Terminated Strings in C
  • Scanf String With Spaces in C
  • How to Create Formatted Strings in C
  • How to Truncate String in C
  • How to Concatenate String and Int in C
  • How to Trim a String in C

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

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

C Programming Tutorial

  • Character Array and Character Pointer in C

Last updated on July 27, 2020

In this chapter, we will study the difference between character array and character pointer. Consider the following example:

Can you point out similarities or differences between them?

The similarity is:

The type of both the variables is a pointer to char or (char*) , so you can pass either of them to a function whose formal argument accepts an array of characters or a character pointer.

Here are the differences:

arr is an array of 12 characters. When compiler sees the statement:

c language assign string to char array

On the other hand when the compiler sees the statement.

It allocates 12 consecutive bytes for string literal "Hello World" and 4 extra bytes for pointer variable ptr . And assigns the address of the string literal to ptr . So, in this case, a total of 16 bytes are allocated.

c language assign string to char array

We already learned that name of the array is a constant pointer. So if arr points to the address 2000 , until the program ends it will always point to the address 2000 , we can't change its address. This means string assignment is not valid for strings defined as arrays.

On the contrary, ptr is a pointer variable of type char , so it can take any other address. As a result string, assignments are valid for pointers.

c language assign string to char array

After the above assignment, ptr points to the address of "Yellow World" which is stored somewhere in the memory.

Obviously, the question arises so how do we assign a different string to arr ?

We can assign a new string to arr by using gets() , scanf() , strcpy() or by assigning characters one by one.

Recall that modifying a string literal causes undefined behavior, so the following operations are invalid.

Using an uninitialized pointer may also lead to undefined undefined behavior.

Here ptr is uninitialized an contains garbage value. So the following operations are invalid.

We can only use ptr only if it points to a valid memory location.

Now all the operations mentioned above are valid. Another way we can use ptr is by allocation memory dynamically using malloc() or calloc() functions.

Let's conclude this chapter by creating dynamic 1-d array of characters.

Expected Output:

Load Comments

  • Intro to C Programming
  • Installing Code Blocks
  • Creating and Running The First C Program
  • Basic Elements of a C Program
  • Keywords and Identifiers
  • Data Types in C
  • Constants in C
  • Variables in C
  • Input and Output in C
  • Formatted Input and Output in C
  • Arithmetic Operators in C
  • Operator Precedence and Associativity in C
  • Assignment Operator in C
  • Increment and Decrement Operators in C
  • Relational Operators in C
  • Logical Operators in C
  • Conditional Operator, Comma operator and sizeof() operator in C
  • Implicit Type Conversion in C
  • Explicit Type Conversion in C
  • if-else statements in C
  • The while loop in C
  • The do while loop in C
  • The for loop in C
  • The Infinite Loop in C
  • The break and continue statement in C
  • The Switch statement in C
  • Function basics in C
  • The return statement in C
  • Actual and Formal arguments in C
  • Local, Global and Static variables in C
  • Recursive Function in C
  • One dimensional Array in C
  • One Dimensional Array and Function in C
  • Two Dimensional Array in C
  • Pointer Basics in C
  • Pointer Arithmetic in C
  • Pointers and 1-D arrays
  • Pointers and 2-D arrays
  • Call by Value and Call by Reference in C
  • Returning more than one value from function in C
  • Returning a Pointer from a Function in C
  • Passing 1-D Array to a Function in C
  • Passing 2-D Array to a Function in C
  • Array of Pointers in C
  • Void Pointers in C
  • The malloc() Function in C
  • The calloc() Function in C
  • The realloc() Function in C
  • String Basics in C
  • The strlen() Function in C
  • The strcmp() Function in C
  • The strcpy() Function in C
  • The strcat() Function in C
  • Array of Strings in C
  • Array of Pointers to Strings in C
  • The sprintf() Function in C
  • The sscanf() Function in C
  • Structure Basics in C
  • Array of Structures in C
  • Array as Member of Structure in C
  • Nested Structures in C
  • Pointer to a Structure in C
  • Pointers as Structure Member in C
  • Structures and Functions in C
  • Union Basics in C
  • typedef statement in C
  • Basics of File Handling in C
  • fputc() Function in C
  • fgetc() Function in C
  • fputs() Function in C
  • fgets() Function in C
  • fprintf() Function in C
  • fscanf() Function in C
  • fwrite() Function in C
  • fread() Function in C

Recent Posts

  • Machine Learning Experts You Should Be Following Online
  • 4 Ways to Prepare for the AP Computer Science A Exam
  • Finance Assignment Online Help for the Busy and Tired Students: Get Help from Experts
  • Top 9 Machine Learning Algorithms for Data Scientists
  • Data Science Learning Path or Steps to become a data scientist Final
  • Enable Edit Button in Shutter In Linux Mint 19 and Ubuntu 18.04
  • Python 3 time module
  • Pygments Tutorial
  • How to use Virtualenv?
  • Installing MySQL (Windows, Linux and Mac)
  • What is if __name__ == '__main__' in Python ?
  • Installing GoAccess (A Real-time web log analyzer)
  • Installing Isso
  • Getting started with C Language
  • Best C Programming Courses
  • Awesome Book
  • Awesome Community
  • Awesome Tutorial
  • Awesome YouTube
  • — character classification & conversion
  • Aliasing and effective type
  • Command-line arguments
  • Common C programming idioms and developer practices
  • Common pitfalls
  • Compilation
  • Compound Literals
  • Constraints
  • Create and include header files
  • Declaration vs Definition
  • Declarations
  • Enumerations
  • Error handling
  • Files and I/O streams
  • Formatted Input/Output
  • Function Parameters
  • Function Pointers
  • Generic selection
  • Identifier Scope
  • Implementation-defined behaviour
  • Implicit and Explicit Conversions
  • Initialization
  • Inline assembly
  • Interprocess Communication (IPC)
  • Iteration Statements/Loops: for, while, do-while
  • Jump Statements
  • Linked lists
  • Literals for numbers, characters and strings
  • Memory management
  • Multi-Character Character Sequence
  • Multithreading
  • Pass 2D-arrays to functions
  • Preprocessor and Macros
  • Random Number Generation
  • Selection Statements
  • Sequence points
  • Side Effects
  • Signal handling
  • Standard Math
  • Storage Classes
  • Basic introduction to strings
  • Calculate the Length: strlen()
  • Comparsion: strcmp(), strncmp(), strcasecmp(), strncasecmp()
  • Convert Strings to Number: atoi(), atof() (dangerous, don't use them)
  • Copy and Concatenation: strcpy(), strcat()
  • Copying strings
  • Creating Arrays of Strings
  • Find first/last occurrence of a specific character: strchr(), strrchr()
  • Iterating Over the Characters in a String
  • Safely convert Strings to Number: strtoX functions
  • string formatted data read/write
  • String literals
  • strspn and strcspn
  • Tokenisation: strtok(), strtok_r() and strtok_s()
  • Zeroing out a string
  • Structure Padding and Packing
  • Testing frameworks
  • Threads (native)
  • Type Qualifiers
  • Undefined behavior
  • Variable arguments

C Language Strings Creating Arrays of Strings

An array of strings can mean a couple of things:

  • An array whose elements are char * s
  • An array whose elements are arrays of char s

We can create an array of character pointers like so:

Remember: when we assign string literals to char * , the strings themselves are allocated in read-only memory. However, the array string_array is allocated in read/write memory. This means that we can modify the pointers in the array, but we cannot modify the strings they point to.

In C, the parameter to main argv (the array of command-line arguments passed when the program was run) is an array of char * : char * argv[] .

We can also create arrays of character arrays. Since strings are arrays of characters, an array of strings is simply an array whose elements are arrays of characters:

This is equivalent to:

Note that we specify 4 as the size of the second dimension of the array; each of the strings in our array is actually 4 bytes since we must include the null-terminating character.

Got any C Language Question?

pdf

  • Advertise with us
  • Privacy Policy

Get monthly updates about new articles, cheatsheets, and tricks.

Learn C practically and Get Certified .

Popular Tutorials

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

  • Keywords & Identifier
  • Variables & Constants
  • C Data Types
  • C Input/Output
  • C Operators
  • C Introduction Examples

C Flow Control

  • C if...else
  • C while Loop
  • C break and continue
  • C switch...case
  • C Programming goto
  • Control Flow Examples

C Functions

  • C Programming Functions
  • C User-defined Functions
  • C Function Types
  • C Recursion
  • C Storage Class
  • C Function Examples
  • C Programming Arrays
  • C Multi-dimensional Arrays
  • C Arrays & Function
  • C Programming Pointers
  • C Pointers & Arrays
  • C Pointers And Functions
  • C Memory Allocation
  • Array & Pointer Examples

C Programming Strings

  • C Programming String
  • C String Functions
  • C String Examples

Structure And Union

  • C Structure
  • C Struct & Pointers
  • C Struct & Function
  • C struct Examples

C Programming Files

  • C Files Input/Output

C Files Examples

Additional Topics

  • C Enumeration
  • C Preprocessors
  • C Standard Library
  • C Programming Examples

String Manipulations In C Programming Using Library Functions

  • Find the Frequency of Characters in a String
  • Remove all Characters in a String Except Alphabets
  • Sort Elements in Lexicographical Order (Dictionary Order)

C Input Output (I/O)

In C programming, a string is a sequence of characters terminated with a null character \0 . For example:

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 of strings in C programming

  • How to declare a string?

Here's how you can declare strings:

string declaration in C programming

Here, we have declared a string of 5 characters.

  • How to initialize strings?

You can initialize strings in a number of ways.

Initialization of strings in C programming

Let's take another example:

Here, we are trying to assign 6 characters (the last character is '\0' ) to a char array having 5 characters. This is bad and you should never do this.

Assigning Values to Strings

Arrays and strings are second-class citizens in C; they do not support the assignment operator once it is declared. For example,

Note: Use the strcpy() function to copy the string instead.

Read String from the user

You can use the scanf() function to read a string.

The scanf() function reads the sequence of characters until it encounters whitespace (space, newline, tab, etc.).

Example 1: scanf() to read a string

Even though Dennis Ritchie was entered in the above program, only "Dennis" was stored in the name string. It's because there was a space after Dennis .

Also notice that we have used the code name instead of &name with scanf() .

This is because name is a char array, and we know that array names decay to pointers in C.

Thus, the  name  in  scanf() already points to the address of the first element in the string, which is why we don't need to use & .

How to read a line of text?

You can use the fgets() function to read a line of string. And, you can use puts() to display the string.

Example 2: fgets() and puts()

Here, we have used fgets() function to read a string from the user.

fgets(name, sizeof(name), stdlin); // read string

The sizeof(name) results to 30. Hence, we can take a maximum of 30 characters as input which is the size of the  name string.

To print the string, we have used puts(name); .

Note: The gets() function can also be to take input from the user. However, it is removed from the C standard. It's because gets() allows you to input any length of characters. Hence, there might be a buffer overflow.

Passing Strings to Functions

Strings can be passed to a function in a similar way as arrays. Learn more about passing arrays to a function .

Example 3: Passing string to a Function

Strings and pointers.

Similar like arrays, string names are "decayed" to pointers. Hence, you can use pointers to manipulate elements of the string. We recommended you to check C Arrays and Pointers before you check this example.

Example 4: Strings and Pointers

Commonly used string functions.

  • strlen() - calculates the length of a string
  • strcpy() - copies a string to another
  • strcmp() - compares two strings
  • strcat() - concatenates two strings

Table of Contents

  • Read and Write String: gets() and puts()
  • Passing strings to a function
  • Strings and pointers
  • Commonly used string functions

Video: C Strings

Sorry about that.

Related Tutorials

Relationship Between Arrays and Pointers

Guru99

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

Barbara Thompson

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 .

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.

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.
  • Dynamic Memory Allocation in C using malloc(), calloc() Functions
  • Type Casting in C: Type Conversion, Implicit, Explicit with Example
  • C Programming Tutorial PDF for Beginners
  • 13 BEST C Programming Books for Beginners (2024 Update)
  • Difference Between C and Java
  • Difference Between Structure and Union in C
  • Top 100 C Programming Interview Questions and Answers (PDF)
  • calloc() Function in C Library with Program EXAMPLE
  • Now Trending:
  • How do I check if a list...
  • How do I concatenate two...
  • How to find the index of...
  • How to make a dictionary...

2D character array-String array-Declaration and initialization

In this C Programming tutorial, we will discuss 2D character arrays in detail and will discuss how to declare, initialize and use 2D character arrays or String arrays.

Table of Contents

1. What is 2D character array in C?

We have successfully learned the basic concepts  and different  library functions  that C Programming offers. Another interesting concept is the use of 2D character arrays. In the previous tutorial, we already saw that string is nothing but an array of characters that ends with a ‘\0’ .

2D character arrays are very similar to 2D integer arrays . We store the elements and perform other operations in a similar manner. A 2D character array is more like a String array . It allows us to store multiple strings under the same name.

2. How to Declaration and Initialization a 2D character array?

A 2D character array is declared in the following manner:

The order of the subscripts is important during declaration. The first subscript [5] represents the number of Strings that we want our array to contain and the second subscript [10] represents the length of each String. This is static memory allocation. We are giving 5*10=50 memory locations for the array elements to be stored in the array.

Initialization of the character array occurs in this manner:

Let’s see the diagram below to understand how the elements are stored in the memory location:

2D char array

The areas marked in green show the memory locations that are reserved for the array but are not used by the string. Each character occupies 1 byte of storage from the memory.

3. How to take 2D array Data input from user?

In order to take string data input from the user we need to follow the following syntax:

Here we see that the second subscript remains [0] . This is because it shows the length of the string and before entering any string the length of the string is 0 .

4. Printing the array elements

The way a 2D character array is printed is not the same as a 2D integer array. This is because we see that all the spaces in the array are not occupied by the string entered by the user.

If we display it in the same way as a 2D integer array we will get unnecessary garbage values in unoccupied spaces. Here is how we can display all the string elements:

This format will print only the string contained in the index numbers specified and eliminate any garbage values after ‘\0’ . All the string library functions that we have come across in the previous tutorials can be used for the operations on strings contained in the string array. Each string can be referred to in this form:

where [i] is the index number of the string that needs to be accessed by library functions.

5. Program to search for a string in the string array

Let’s implement a program to search for a string(a char array) entered by the user in a 2D char array or a string array (also entered by the user):

Helpful Links

Please follow C Programming tutorials or the menu in the sidebar for the complete tutorial series.

Also for the example C programs please refer to C Programming Examples . All examples are hosted on Github .

Recommended Books

An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding

Do not forget to share and Subscribe.

Happy coding!! ?

Recommended -

guest

  • Algorithm Tutorials
  • C Programming Examples
  • C Programming tutorials
  • Complete Python Tutorials – Beginner to Advanced
  • Data Structure Tutorials
  • Python Programming Examples – Basic to Advanced
  • Subscribe to our Newsletter !!
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP

Related Articles

  • Solve Coding Problems
  • Convert std::string to LPCWSTR in C++
  • Print all the non-repeating words from the two given sentences
  • Check if expression contains redundant bracket or not | Set 2
  • Program to count occurrence of a given character in a string
  • Different ways to access characters in a given String in C++
  • C++ program to check whether a String is a Pangram or not
  • std::string::rfind in C++ with Examples
  • Difference between concatenation of strings using (str += s) and (str = str + s)
  • Insert a Character in a Rotated String
  • Arrays and Strings in C++
  • Split numeric, alphabetic and special symbols from a String
  • Extract all integers from string in C++
  • Quick way to check if all the characters of a string are same
  • Remove comments from a given C/C++ program
  • starts_with() and ends_with() in C++20 with Examples
  • Print all occurrences of a string as a substring in another string
  • Program to Parse a comma separated string in C++
  • How to input a comma separated string in C++?
  • Processing strings using std::istringstream

Convert character array to string in C++

This article shows how to convert a character array to a string in C++.  The std::string in c++ has a lot of inbuilt functions which makes implementation much easier than handling a character array. Hence, it would often be easier to work if we convert a character array to string. Examples:    

  • Get the character array and its size.
  • Create an empty string.
  • Iterate through the character array.
  • As you iterate keep on concatenating the characters we encounter in the character array to the string.
  • Return the string.

Below is the implementation of the above approach.

  • Declare a string (i.e, an object of the string class) and while doing so give the character array as its parameter for its constructor.
  • Use the syntax: string string_name(character_array_name);
  • Declare a string.
  • Use the overloaded ‘=’ operator to assign the characters in the character array to the string.

Please Login to comment...

  • cpp-strings
  • C++ Programs
  • wilsonng234

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. How to convert string to char array in C++

    c language assign string to char array

  2. Implementing C# String Array

    c language assign string to char array

  3. C++ Char Data Type with Examples (2023)

    c language assign string to char array

  4. Strings in C

    c language assign string to char array

  5. Strings in C and Char Arrays Tutorial and Important Interview MCQ

    c language assign string to char array

  6. 38. Two D char Array for String in C++ (Hindi)

    c language assign string to char array

VIDEO

  1. MALAYALM TEXT & VARIABLE #malayalam #block #code #coding #stem #text #variable

  2. Array : Can't assign string to pointer inside struct

  3. c++ part 2 (Arrays)

  4. create empty dict in python

  5. Arrays in C++

  6. Array C++

COMMENTS

  1. c

    10 Answers Sorted by: 90 When initializing an array, C allows you to fill it with values. So char s [100] = "abcd"; is basically the same as int s [3] = { 1, 2, 3 }; but it doesn't allow you to do the assignment since s is an array and not a free pointer. The meaning of s = "abcd"

  2. Array of Strings in C

    Syntax: char variable_name [r] = {list of string}; Here, var_name is the name of the variable in C. r is the maximum number of string values that can be stored in a string array. c is the maximum number of character values that can be stored in each string array. Example: C #include <stdio.h> int main () { char arr [3] [10] = {"Geek",

  3. How to Initialize Char Array in C

    Another useful method to initialize a char array is to assign a string value in the declaration statement. The string literal should have fewer characters than the length of the array; otherwise, there will be only part of the string stored and no terminating null character at the end of the buffer.

  4. String and Character Arrays in C Language

    Syntax: strcat ("hello", "world"); strcat () will add the string "world" to "hello" i.e ouput = helloworld. 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.

  5. Array of Strings in C

    Use 2D Array Notation to Declare Array of Strings in C. Strings in C are simply a sequence of chars stored in a contiguous memory region. One distinction about character strings is that there is a terminating null byte \0 stored at the end of the sequence, denoting one string's end. If we declare a fixed array of char using the [] notation, then we can store a string consisting of the same ...

  6. C String

    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.

  7. Array of Strings in C

    Array of Strings in C Last updated on July 27, 2020 What is an Array of Strings? A string is a 1-D array of characters, so an array of strings is a 2-D array of characters. Just like we can create a 2-D array of int, float etc; we can also create a 2-D array of character or array of strings. Here is how we can declare a 2-D array of characters.

  8. Character Array and Character Pointer in C

    We can assign a new string to arr by using gets (), scanf (), strcpy () or by assigning characters one by one. 1 2 3 4 5 6 7 8 9 10 11 12 13 gets(arr); scanf("%s", arr); strcpy(arr, "new string"); arr[0] = 'R'; arr[1] = 'e'; arr[2] = 'd'; arr[3] = ' '; arr[4] = 'D'; arr[5] = 'r'; arr[6] = 'a'; arr[7] = 'g'; arr[8] = 'o'; arr[9] = 'n';

  9. C Language Tutorial => Creating Arrays of Strings

    An array whose elements are arrays of chars; We can create an array of character pointers like so: char * string_array[] = { "foo", "bar", "baz" }; Remember: when we assign string literals to char *, the strings themselves are allocated in read-only memory. However, the array string_array is allocated in read/write memory. This means that we ...

  10. Strings in C (With Examples)

    Here's how you can declare strings: char s [5]; String Declaration in C Here, we have declared a string of 5 characters. How to initialize strings? You can initialize strings in a number of ways. char c [] = "abcd"; char c [50] = "abcd"; char c [] = {'a', 'b', 'c', 'd', '\0'}; char c [5] = {'a', 'b', 'c', 'd', '\0'}; String Initialization in C

  11. Working with character arrays and "strings" in C

    Learn some basics on character arrays and strings in C. Learn how to declare, modify, output, and manipulate character arrays and C strings.Hope you enjoyed ...

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

  13. Convert String to Char Array in C++

    The c_str () function is used to return a pointer to an array that contains a null-terminated sequence of characters representing the current value of the string. const char* c_str () const; If there is an exception thrown then there are no changes in the string.

  14. Convert String to Char Array and Char Array to String in C++

    Using a for loop. 1. The c_str () and strcpy () function in C++. C++ c_str () function along with C++ String strcpy () function can be used to convert a string to char array easily. The c_str () method represents the sequence of characters in an array of string followed by a null character ('\0'). It returns a null pointer to the string.

  15. How to Initialize & Declare 2D character array in C?

    In order to take string data input from the user we need to follow the following syntax: for(i=0 ;i<5 ;i++ ) scanf("%s",&name[i] [0]); Here we see that the second subscript remains [0]. This is because it shows the length of the string and before entering any string the length of the string is 0. 4.

  16. How to "re-assign" a character string to an existing char array?

    strcpy (myArray, "test 123"); 2) there's no need to "clear" the array before assigning a new string. But if you really want this there are 2 ways. a) copy an empty string: strcpy (myArray, ""); b) assign 0 to first array element: myArray [0] = 0; - since 0 is the string terminator this is the same as copying an empty string to myArray.

  17. Convert character array to string in C++

    Method 1: Approach: Get the character array and its size. Create an empty string. Iterate through the character array. As you iterate keep on concatenating the characters we encounter in the character array to the string. Return the string. Below is the implementation of the above approach. C++ #include <bits/stdc++.h> using namespace std;

  18. c++

    8 Answers Sorted by: 26 Strictly speaking, an array is not a pointer! And an array ( base address of the array ) cant be a modifiable lvalue. ie it cannot appear on the left hand side of an assignment operator.Arrays decay into pointers only in certain circumstances. Read this SO post to learn when arrays decay into pointers.

  19. c++

    You should use strcpy (s1, "apple") to do this, though it differs slightly in behaviour: it will only set s1 [5] to 0/NUL, with [6] onwards unaffected (if s1 is on the stack or heap they'll be uninitialised and reading from them will be undefined behaviour). Most things you'd want to do with s1 won't benefit from initialisation of [6] onwards....

  20. Declare and define a char pointer variable on different lines in C++

    Why is conversion from string literal to 'char*' valid in C but invalid in C++ (4 answers) Closed 12 days ago . I have a script that attempts to identify the word __version__ at the beginning of a line (i.e. ^__version__ as regex) in a text file, and replaces its assignment with a current date string; and I would like to reuse this script ...