How to convert C style strings to std::string and vice versa?
Last Updated :
06 Jul, 2017
What are C style strings?
These strings are array of characters terminating with a NULL character. C style strings can be declared in following ways:
Declaration and initialization
CPP
/* To demonstrate C style strings */
#include<iostream>
using namespace std;
int main()
{
/* Null character has to be added explicitly */
char str1[8] = {'H' , 'E' , 'L' , 'L' , 'O' ,
'-','1','\0' };
/* Compiler implicitly adds Null character */
char str2[] = "HELLO-2" ;
/* Compiler implicitly adds Null character.
Note that string literals are typically stored
as read only */
const char *str3 = "HELLO-3" ;
cout << str1 << endl << str2 << endl << str3;
return 0;
}
Output:
HELLO-1
HELLO-2
HELLO-3
C style strings are operated with very useful functions like
strcpy(),
strlen(),
strpbrk(),
strcat(),
strstr() and many more!(All these functions are member functions of '
cstring' header ).
What is a std::string?
C++ standard library contains functions and classes. String is one of its classes. Here we deal with an object of string class. This std::string takes care of itself and manages its own memory.
Declaration and initialization
CPP
/* To demonstrate std::string */
#include<iostream>
#include<string>
using namespace std;
int main()
{
/* s becomes object of class string. */
string s;
/* Initializing with a value. */
s = "HELLO";
/* Printing the value */
cout << s;
return 0;
}
Output:
HELLO
Converting C-String to a std::string.
But why do we need this transformation? From a C string to a std::string? It is because
- Std::string manages its own space. So programmer don’t need to worry about memory , unlike C strings (Since they are array of characters)
- They are easy to operate. ‘+’ operator for concatenation, '=' for assignment, can be compared using regular operators.
- string::find() and many other functions can be implemented on std::string and not on C-Strings so this becomes handy.
- Iterators can be used in std::string and not in C-strings.
And many more! Here is the code for it:-
CPP
/* To demonstrate C style string to std::string */
#include<bits/stdc++.h>
using namespace std;
int main()
{
/*Initializing a C-String */
const char *a = "Testing";
cout << "This is a C-String : "<< a << endl;
/* This is how std::string s is assigned
though a C string ‘a’ */
string s(a);
/* Now s is a std::string and a is a C-String */
cout << "This is a std::string : "<< s << endl;
return 0;
}
Output:
This is a C-String : Testing
This is a std::string : Testing
The above conversion also works for character array.
// Character array to std::string conversion
char a[] = "Testing";
string s(a);
Converting a std::string to a C style string
Why do we need this transformation? From std::string to a C string?
- It is because there are several powerful functions in header that makes our work very much easier.
- atoi() , itoa() , and many more functions work with C strings only.
You can think of other reasons too!
Here is the code for conversion:-
CPP
/* To demonstrate std::string to C style string */
#include<iostream>
#include<string> /* This header contains string class */
using namespace std;
int main()
{
/* std::string initialized */
string s = "Testing";
cout << "This is a std::string : "<< s << endl;
/* Address of first character of std::string is
stored to char pointer a */
char *a = &(s[0]);
/* Now 'a' has address of starting character
of string */
printf("%s\n", a);
return 0;
}
Output:
This is a std::string : Testing
This is a C-String : Testing
std::string also has a function
c_str() that can be used to get a null terminated character array.
CPP
/* To demonstrate std::string to C style string using
c_str() */
#include<bits/stdc++.h>
using namespace std;
int main()
{
/* std::string initialized */
string s = "Testing";
cout << "This is a std::string : "<< s << endl;
// c_str returns null terminated array of characters
const char *a = s.c_str();
/* Now 'a' has address of starting character
of string */
printf("%s\n", a);
return 0;
}
Output:
This is a std::string : Testing
This is a C-String : Testing
Both C strings and std::strings have their own advantages. One should know conversion between them, to solve problems easily and effectively.
Related articles:
C++ string class and its applications | Set 1
C++ string class and its applications | Set 2
Similar Reads
How to write long strings in Multi-lines C/C++? Image a situation where we want to use or print a long long string in C or C++, how to do this? In C/C++, we can break a string at any point in the middle using two double quotes in the middle. Below is a simple example to demonstrate the same. C #include<stdio.h> int main() { // We can put tw
2 min read
How to split a string in C/C++, Python and Java? Splitting a string by some delimiter is a very common task. For example, we have a comma-separated list of items from a file and we want individual items in an array. Almost all programming languages, provide a function split a string by some delimiter. In C: // Splits str[] according to given delim
7 min read
Converting Number to String in C++ In C++, converting integers to strings or converting numbers to strings or vice-versa is actually a big paradigm shift in itself. In general or more specifically in competitive programming there are many instances where we need to convert a number to a string or string to a number. Let's look at som
4 min read
Write one line functions for strcat() and strcmp() Recursion can be used to do both tasks in one line. Below are one line implementations for stracat() and strcmp(). C /* my_strcat(dest, src) copies data of src to dest. To do so, it first reaches end of the string dest using recursive calls my_strcat(++dest, src). Once end of dest is reached, data i
2 min read
C++ string class and its applications In C++ we can store string by one of the two ways â C style stringsstring class (discussed in this post) In this post, the second method is discussed. string class is part of C++ library that supports a lot much functionality over C style strings. C++ string class internally uses char array to store
6 min read