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
  • Standard Template Library
  • STL Priority Queue
  • STL Interview Questions
  • STL Cheatsheet
  • C++ Templates
  • C++ Functors
  • C++ Iterators
  • std::string::compare() in C++
  • std::string::push_back() in C++
  • std::string::data() in C++
  • std::basic_string::max_size in C++
  • How to convert C style strings to std::string and vice versa?
  • std::string class in C++
  • lexicographical_compare() in C++ STL
  • std::string::append() in C++
  • std::basic_string::at vs std::basic_string::operator[]
  • Conversion of whole String to uppercase or lowercase using STL in C++
  • char* vs std:string vs char[] in C++
  • <strings> library in C++ STL
  • std::string::insert() in C++
  • Memset in C++
  • std::string::resize() in C++
  • How to convert a single character to string in C++?
  • std::find in C++
  • std::basic_string::operator[] in C++
  • std::strncmp() in C++

std::string::assign() in C++

The member function assign() is used for the assignments, it assigns a new value to the string, replacing its current contents.  Syntax 1: Assign the value of string str. 

Output: 

Syntax 2: Assigns at most str_num characters of str starting with index str_idx. It throws out_of _range if str_idx > str. size(). 

Syntax 3: Assign the characters of the C-string cstr. It throws length_error if the resulting size exceeds the maximum number of characters. 

Syntax 4: Assigns chars_len characters of the character array chars. It throws length_error if the resulting size exceeds the maximum number of characters. 

Syntax 5: Assigns num occurrences of character c. It throws length_error if num is equal to string::npos 

Syntax 6: Assigns all characters of the range [beg, end). It throws length_error if range outruns the actual content of string. 

If you like GeeksforGeeks(We know you do!) and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected].

Please Login to comment...

  • cpp-strings-library
  • How to Delete Whatsapp Business Account?
  • Discord vs Zoom: Select The Efficienct One for Virtual Meetings?
  • Otter AI vs Dragon Speech Recognition: Which is the best AI Transcription Tool?
  • Google Messages To Let You Send Multiple Photos
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

C Functions

C structures.

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 :

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

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

[email protected]

Top Tutorials

Top references, top examples, get certified.

C Strings - Declaring Strings in C

C++ Course: Learn the Essentials

In C programming, a string is essentially an array of characters terminated by the null character '\0' . Unlike a generic character array, a C string always concludes with this unique terminator, indicating its endpoint. Represented as a one-dimensional array, each character within occupies one byte of memory. For instance, when declaring " char s[10] ", the array is implicitly initialized with a null terminator. This distinct characteristic ensures that operations on C strings rely on this sentinel value to determine string boundaries, facilitating efficient string manipulation and processing in C programs.

Declaring a String in C

A String in C is an array with character as a data type. C does not directly support string as a data type, as seen in other programming languages like C++. Hence, character arrays must be used to display a string in C. The general syntax of declaring a string in C is as follows:

Thus, the classic declaration can be made as follows:

It is vital to note that we should always account for an extra space used by the null character(\0).

Highlights:

  • Character arrays are used for declaring strings in C.
  • The general syntax for declaring them is:

Initializing a String in C

There are four methods of initializing a string in C:

1. Assigning a string literal with size

We can directly assign a string literal to a character array keeping in mind to keep the array size at least one more than the length of the string literal that will be assigned to it.

Note While setting the initial size, we should always account for one extra space used by the null character. If we want to store a string of size n , we should set the initial size to be n+1 .

For example:

The string length here is 7, but we have kept the size to be 8 to account for the Null character. The compiler adds the Null character(\0) at the end automatically .

Note: If the array cannot accommodate the entire string, it only takes characters based on its space. For example:

2. Assigning a string literal without size

It is also possible to directly assign a string literal to a character array without any size. The size gets determined automatically by the compiler at compile time.

The critical thing to remember is that the name of the string, here " str " acts as a pointer because it is an array.

3. Assigning character by character with size

We can also assign a string character by character. However, it is essential to set the end character as '\0'. For example:

4. Assigning character by character without size

Like assigning directly without size, we also assign character by character with the Null Character at the end. The compiler will determine the size of the string automatically.

Assigning character by character without size

Highlights: There are four methods of initializing a string in C:

  • Assigning a string literal with size.
  • Assigning a string literal without size.
  • Assigning character by character with size.
  • Assigning character by character without size.

Assign value to strings

  • Character arrays cannot be assigned a string literal with the '=' operator once they have been declared.

This will cause a compilation error since the assignment operations are not supported once strings are declared. To overcome this, we can use the following two methods:

  • Assign the value to a character array while initializing it, explained above.
  • We can use the strcpy() function to copy the value we want to assign to the character array. The syntax for strcpy() is as follows:

It copies the string pointed by the source (including the null character) to the destination. For example:

This assigns the value to the string.

Note - It is vital to make sure the value assigned should have a length less than or equal to the maximum size of the character array.

  • Assignment can either be done at the initialization time or by using the strcpy() function.

Read String from the user

The most common operation used for reading a string is scanf() , which reads a sequence of characters until it encounters whitespace (i.e., space, newline, tab, etc.). The following section explains the method of taking input with whitespace. For example,

If we provide the following input :

We get the following Output :

As we can see, scanf() stops taking input once it encounters whitespace.

  • The format specifier used to input and output strings in C is %s .
  • You might notice that generally, the variable's name is preceded by a & operator with scanf() . This is not the case here, as the character array is a pointer that points to the address of the first character of the array. Hence the address operator ( & ) doesn't need to be used.
  • Strings in C can be read using scanf() . However, it only reads until it encounters whitespace.

How to read a line of text?

The scanf() operation cannot read strings with spaces as it automatically stops reading when it encounters whitespace. To read and print strings with whitespace, we can use the combination of fgets() and puts() :

  • fgets() The fgets() function is used to read a specified number of characters. Its declaration looks as follows:

name_of_string *: It is the variable in which the string is going to be stored. number_of_characters : The maximum length of the string should be read. stdin : It is the filehandle from where the string is to be read.

  • puts() puts() is very convenient for displaying strings.

name_of_string : It is the variable in which the string will be stored.

An example using both functions:

In the above example, we can see that the entire string with the whitespace was stored and displayed, thus showing us the power of fgets() and puts() .

  • The combination of fgets() and puts() is used to tackle the problem of reading a line of text with whitespace.
  • Syntax for fgets() :
  • Syntax for puts() :

Passing strings to functions

As strings are simply character arrays, we can pass strings to function in the same way we pass an array to a function, either as an array or as a pointer. Let's understand this with the following program:

As we can see, both of them yield the same Output.

  • String can be passed to functions as a character array or even in the form of a pointer.

Strings and Pointers

As we have seen, strings in C are represented by character arrays which act as pointers. Hence, we can use pointers to manipulate or even perform operations on the string.

using pointers to manipulate or perform operations on a string

Note: Since character arrays act like pointers, we can easily use pointers to manipulate strings.

String Example in C

Here is a program that demonstrates everything we have learned in this article:

You can run and check your code in this Online C Compiler .

Difference between character Array and String literal

Before actually jumping to the difference, let us first recap string literals. A string literal is a sequence of zero or more multibyte characters enclosed in double quotes, as in "xyz". String literals are not modifiable (and are placed in read-only memory). An attempt to alter their values results in undefined behavior.

String literals can be used to initialize arrays. We have seen multiple examples of this throughout the article. Now, let us see the differences using the following examples:

This statement creates a character array that has been assigned a string literal. It behaves as a usual array with which we can perform regular operations, including modification. The only thing to remember is that although we have initialized 7 elements, its size is 8, as the compiler adds the \0 at the end.

The above statement creates a pointer that points to the string literal, i.e. to the first character of the string literal. Since we now know that string literals are stored in a read-only memory location, thus alteration is not allowed.

Note - While printing string literals, it is defined to declare them as constants like:

This prevents the warning we get while using printf() with string literals.

  • String literals are stored on the read-only memory part of most compilers. Hence they cannot be modified.
  • With character arrays, we can perform the usual operations on arrays including modification.
  • Pointers that point to the string literal cannot be modified, just like string literals.
  • Strings in C are declared with character arrays, a linear sequence of characters.
  • The compiler automatically appends the Null character ( \0 ) at the end of character arrays.
  • There are four ways of initializing a string.
  • Strings in C do not support the assignment operation once declared.
  • Strings in C can be read using scanf() ; however, it only reads until it encounters whitespace.
  • The combination of fgets() and puts() tacked the problem of reading a line of text with spaces.
  • A string can be passed to a function as a character array or in the form of a pointer.
  • Since character arrays act like pointers, we can easily use pointers to manipulate strings.
  • We can modify character arrays; however, it is impossible to do so with pointers pointing to string literals.

cppreference.com

Std::basic_string<chart,traits,allocator>:: assign.

Replaces the contents of the string.

[ edit ] Parameters

[ edit ] return value, [ edit ] complexity, [ edit ] exceptions.

              propagate_on_container_move_assignment :: value ||

If the operation would result in size ( ) >   max_size ( ) , throws std::length_error .

If an exception is thrown for any reason, this function has no effect ( strong exception safety guarantee ).

[ edit ] Example

[ edit ] defect reports.

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

[ edit ] See also

  • conditionally noexcept
  • Recent changes
  • Offline version
  • What links here
  • Related changes
  • Upload file
  • Special pages
  • Printable version
  • Permanent link
  • Page information
  • In other languages
  • This page was last modified on 17 August 2023, at 01:57.
  • This page has been accessed 185,823 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

std::basic_string:: assign

Replaces the contents of the string.

1) Replaces the contents with count copies of charactor ch

2) Replaces the contents with a copy of str

3) Replaces the contents with a substring [pos, pos+count) of str . If the requested substring lasts past the end of the string, or if count == npos , the resulting substring is [pos, size()) . If pos >= str. size ( ) , std:: out_of_range is thrown.

4) Replaces the contents with those of str using move semantics. str is in undefined state after the operation.

5) Replaces the contents with the first count characters of character string pointed to by s . s can contain null characters.

6) Replaces the contents with those of null-terminated character string pointed to by s . The length of the string is determined by the first null character.

7) Replaces the contents with copies of the characters in the range [first, last)

8) Replaces the contents with those of the initializer list ilist .

[ edit ] Parameters

[ edit ] return value, [ edit ] complexity.

1) linear in count

2) linear in size of str

3) linear in count

4) constant. If alloc is given and alloc ! = other. get_allocator ( ) , then linear.

5) linear in count

6) linear in size of s

7) linear in distance between first and last

8) linear in size of init

[ edit ] Example

[ edit ] see also.

  • Todo no example
  • <cassert> (assert.h)
  • <cctype> (ctype.h)
  • <cerrno> (errno.h)
  • C++11 <cfenv> (fenv.h)
  • <cfloat> (float.h)
  • C++11 <cinttypes> (inttypes.h)
  • <ciso646> (iso646.h)
  • <climits> (limits.h)
  • <clocale> (locale.h)
  • <cmath> (math.h)
  • <csetjmp> (setjmp.h)
  • <csignal> (signal.h)
  • <cstdarg> (stdarg.h)
  • C++11 <cstdbool> (stdbool.h)
  • <cstddef> (stddef.h)
  • C++11 <cstdint> (stdint.h)
  • <cstdio> (stdio.h)
  • <cstdlib> (stdlib.h)
  • <cstring> (string.h)
  • C++11 <ctgmath> (tgmath.h)
  • <ctime> (time.h)
  • C++11 <cuchar> (uchar.h)
  • <cwchar> (wchar.h)
  • <cwctype> (wctype.h)

Containers:

  • C++11 <array>
  • <deque>
  • C++11 <forward_list>
  • <list>
  • <map>
  • <queue>
  • <set>
  • <stack>
  • C++11 <unordered_map>
  • C++11 <unordered_set>
  • <vector>

Input/Output:

  • <fstream>
  • <iomanip>
  • <ios>
  • <iosfwd>
  • <iostream>
  • <istream>
  • <ostream>
  • <sstream>
  • <streambuf>

Multi-threading:

  • C++11 <atomic>
  • C++11 <condition_variable>
  • C++11 <future>
  • C++11 <mutex>
  • C++11 <thread>
  • <algorithm>
  • <bitset>
  • C++11 <chrono>
  • C++11 <codecvt>
  • <complex>
  • <exception>
  • <functional>
  • C++11 <initializer_list>
  • <iterator>
  • <limits>
  • <locale>
  • <memory>
  • <new>
  • <numeric>
  • C++11 <random>
  • C++11 <ratio>
  • C++11 <regex>
  • <stdexcept>
  • <string>
  • C++11 <system_error>
  • C++11 <tuple>
  • C++11 <type_traits>
  • C++11 <typeindex>
  • <typeinfo>
  • <utility>
  • <valarray>

class templates

  • basic_string
  • char_traits
  • C++11 u16string
  • C++11 u32string
  • C++11 stold
  • C++11 stoll
  • C++11 stoul
  • C++11 stoull
  • C++11 to_string
  • C++11 to_wstring
  • string::~string
  • string::string

member functions

  • string::append
  • string::assign
  • C++11 string::back
  • string::begin
  • string::c_str
  • string::capacity
  • C++11 string::cbegin
  • C++11 string::cend
  • string::clear
  • string::compare
  • string::copy
  • C++11 string::crbegin
  • C++11 string::crend
  • string::data
  • string::empty
  • string::end
  • string::erase
  • string::find
  • string::find_first_not_of
  • string::find_first_of
  • string::find_last_not_of
  • string::find_last_of
  • C++11 string::front
  • string::get_allocator
  • string::insert
  • string::length
  • string::max_size
  • string::operator[]
  • string::operator+=
  • string::operator=
  • C++11 string::pop_back
  • string::push_back
  • string::rbegin
  • string::rend
  • string::replace
  • string::reserve
  • string::resize
  • string::rfind
  • C++11 string::shrink_to_fit
  • string::size
  • string::substr
  • string::swap

member constants

  • string::npos

non-member overloads

  • getline (string)
  • operator+ (string)
  • operator<< (string)
  • >/" title="operator>> (string)"> operator>> (string)
  • relational operators (string)
  • swap (string)

std:: string ::operator=

Return value, iterator validity, exception safety.

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Basic CString Operations

  • 7 contributors

This topic explains the following basic CString operations:

Creating CString objects from standard C literal strings

Accessing individual characters in a CString

Concatenating two CString objects

Comparing CString objects

Converting CString objects

Class CString is based on class template CStringT Class . CString is a typedef of CStringT . More exactly, CString is a typedef of an explicit specialization of CStringT , which is a common way to use a class template to define a class. Similarly defined classes are CStringA and CStringW .

CString , CStringA , and CStringW are defined in atlstr.h. CStringT is defined in cstringt.h.

CString , CStringA , and CStringW each get a set of the methods and operators defined by CStringT for use with the string data they support. Some of the methods duplicate and, in some cases, surpass the string services of the C run-time libraries.

Note: CString is a native class. For a string class that is for use in a C++/CLI managed project, use System.String .

Creating CString Objects from Standard C Literal Strings

You can assign C-style literal strings to a CString just as you can assign one CString object to another.

Assign the value of a C literal string to a CString object.

Assign the value of one CString to another CString object.

The contents of a CString object are copied when one CString object is assigned to another. Therefore, the two strings do not share a reference to the actual characters that make up the string. For more information about how to use CString objects as values, see CString Semantics .

To write your application so that it can be compiled for Unicode or for ANSI, code literal strings by using the _T macro. For more information, see Unicode and Multibyte Character Set (MBCS) Support .

Accessing Individual Characters in a CString

You can access individual characters in a CString object by using the GetAt and SetAt methods. You can also use the array element, or subscript, operator ( [ ] ) instead of GetAt to get individual characters. (This resembles accessing array elements by index, as in standard C-style strings.) Index values for CString characters are zero-based.

Concatenating Two CString Objects

To concatenate two CString objects, use the concatenation operators (+ or +=), as follows.

At least one argument to the concatenation operators (+ or +=) must be a CString object, but you can use a constant character string (for example, "big" ) or a char (for example, 'x') for the other argument.

Comparing CString Objects

The Compare method and the == operator for CString are equivalent. Compare , operator== , and CompareNoCase are MBCS and Unicode aware; CompareNoCase is also case-insensitive. The Collate method of CString is locale-sensitive and is often slower than Compare . Use Collate only where you must abide by the sorting rules as specified by the current locale.

The following table shows the available CString comparison functions and their equivalent Unicode/MBCS-portable functions in the C run-time library.

The CStringT class template defines the relational operators (<, <=, >=, >, ==, and !=), which are available for use by CString . You can compare two CStrings by using these operators, as shown in the following example.

Converting CString Objects

For information about converting CString objects to other string types, see How to: Convert Between Various String Types .

Using CString with wcout

To use a CString with wcout you must explicitly cast the object to a const wchar_t* as shown in the following example:

Without the cast, cs is treated as a void* and wcout prints the address of the object. This behavior is caused by subtle interactions between template argument deduction and overload resolution which are in themselves correct and conformant with the C++ standard.

Strings (ATL/MFC) CStringT Class Template Specialization How to: Convert Between Various String Types

Was this page helpful?

Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see: https://aka.ms/ContentUserFeedback .

Submit and view feedback for

Additional resources

IMAGES

  1. C# Tutorial Variables

    c string assign value

  2. Solved 14. In C, what is the correct way to assign a value

    c string assign value

  3. Strings en C++ et comment les créer ?

    c string assign value

  4. Using strings as variables (C++ programming tutorial)

    c string assign value

  5. Array of Strings in C Detailed Explanation Made Easy Lec-70

    c string assign value

  6. Strings in C

    c string assign value

VIDEO

  1. Types of Utility Function Part I (UGC-NET, IAS, IES, RBI, Ist Grade/KVS/PGT)

  2. Can you assign character value to a int data type variable (Core Java Interview Question #182)

  3. One Components: Light / Dark, Localisation LTR / RTL, Responsive Across Devices

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

  5. C++Tutorial for Beginners 33

  6. String variable in C Language || strcpy() function in c || Learn C language in Urdu || Hindi

COMMENTS

  1. c

    The first example doesn't work because you can't assign values to arrays - arrays work (sort of) like const pointers in this respect. What you can do though is copy a new value into the array: strcpy(p.name, "Jane"); Char arrays are fine to use if you know the maximum size of the string in advance, e.g. in the first example you are 100% sure ...

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

  4. ::assign

    Assigns a new value to the string, replacing its current contents. (1) string Copies str. (2) substring Copies the portion of str that begins at the character position subpos and spans sublen characters (or until the end of str, if either str is too short or if sublen is string::npos). (3) c-string Copies the null-terminated character sequence (C-string) pointed by s.

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

  6. C String

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

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

  8. std::string::assign() in C++

    std::string::assign () in C++. The member function assign () is used for the assignments, it assigns a new value to the string, replacing its current contents. Syntax 1: Assign the value of string str. string& string::assign (const string& str) str : is the string to be assigned. Returns : *this.

  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 Strings

    This distinct characteristic ensures that operations on C strings rely on this sentinel value to determine string boundaries, facilitating efficient string manipulation and processing in C programs. ... There are four methods of initializing a string in C: 1. Assigning a string literal with size.

  11. std::basic_string<CharT,Traits,Allocator>:: assign

    std::basic_string<CharT,Traits,Allocator>:: assign. Replaces the contents of the string. 2) Replaces the contents with a copy of str. Equivalent to *this = str;. In particular, allocator propagation may take place.(since C++11) 3) Replaces the contents with a substring [pos,pos + count) of str. If the requested substring lasts past the end of ...

  12. 22.5

    string& string::operator= (char c) These functions assign values of various types to the string. These functions return *this so they can be "chained". Note that there is no assign () function that takes a single char. Sample code: std :: string sString; // Assign a string value. sString = std ::string("One");

  13. std::basic_string::assign

    Replaces the contents of the string. 1) Replaces the contents with count copies of charactor ch. 2) Replaces the contents with a copy of str. 3) Replaces the contents with a substring [pos, pos+count) of str.If the requested substring lasts past the end of the string, or if count == npos, the resulting substring is [pos, size()).If pos >= str. size (), std:: out_of_range is thrown.

  14. ::assign

    Assigns a new value to the string, replacing its current contents. (1) string Copies str. (2) substring Copies the portion of str that begins at the character position subpos and spans sublen characters (or until the end of str, if either str is too short or if sublen is basic_string::npos). (3) c-string Copies the null-terminated character sequence (C-string) pointed by s.

  15. ::operator=

    Assigns a new value to the string, replacing its current contents. (See member function assign for additional assignment options). Parameters str A string object, whose value is either copied (1) or moved (5) if different from *this (if moved, str is left in an unspecified but valid state). s Pointer to a null-terminated sequence of characters.

  16. 17.10

    This means you can initialize the string upon creation, but you can not assign values to it using the assignment operator after that! char str[]{ "string" }; // ok str = "rope"; // not ok! ... Because C-style strings are C-style arrays, you can use std::size() (or in C++20, std::ssize()) to get the length of the string as an array. There are ...

  17. 5.9

    While C-style string literals are fine to use, C-style string variables behave oddly, are hard to work with (e.g. you can't use assignment to assign a C-style string variable a new value), and are dangerous (e.g. if you copy a larger C-style string into the space allocated for a shorter C-style string, undefined behavior will result).

  18. String assignment in C#

    This means that variables of type strings are storage locations whose values are references. In this case, their values are references to instances of string. When you assign a variable of type string to another of type string, the value is copied. In this case, the value is a reference and it is copied by the assignment.

  19. Basic CString Operations

    For a string class that is for use in a C++/CLI managed project, use System.String. Creating CString Objects from Standard C Literal Strings. You can assign C-style literal strings to a CString just as you can assign one CString object to another. Assign the value of a C literal string to a CString object. CString myString = _T("This is a test");

  20. Assigning a value to a char array (String) in C

    Because in C arrays are not modifiable lvalues. So you can either initialize the array: char k[25] = "Dennis"; or, use strcpy to copy: strcpy(k, "Dennis"); If you actually have no need for an array, you can simply use a pointer that points to the string literal. The following is valid:

  21. c++11

    There's a slight problem with the string_assign_method. It's calling the incorrect overload of std::string::assign. You are copying an empty string essentially. You should instead do: str.assign(base, 0, 9);. Benchmark results are unaffected though -

  22. Different ways of adding to a dictionary in C#

    The first version will add a new KeyValuePair to the dictionary, throwing if key is already in the dictionary. The second, using the indexer, will add a new pair if the key doesn't exist, but overwrite the value of the key if it already exists in the dictionary.