How To Convert String To Char In C++

In C++ programming, a string is a form of data that is used to represent text rather than integers. Letters, numbers, symbols, and even spaces can all be found in a string, which are a collection of characters. The object of the class std::string known as string represents a sequence of characters. Strings  can be used for a variety of operations, including concatenation, comparison, conversion, and  many more. Whereas Char is a C++ data type intended for letter storage. Char is an abbreviation for an alphanumeric character. This is an integral type of data, which means that the value is stored as an integer. A tank takes a 1-byte memory size. It also stores a single feature.

Example: String representation

String computer = “Science”;

Example: Character representation

Char computer[6] = {‘H’,’e’,’l’,’l’,’o’};

Why Is There A Need To Convert String to Char in  C++

In computer programming, some languages do not support strings directly. They process a group of characters. Though, to process each character of the string, we required to convert string to character. 

  • Dynamic Memory Allocation – std::string has more overhead, consuming large amounts of memory compared to other means.
  • Support Other Programming Language- std::string does not work with the old C code. therefore we require to convert string to char. For example, to process strings in C, we need an array of characters. 
  • Character or Code Corrections: Using the simple string has a much higher chance of accidentally printing the password to logs or other unsecured locations where the char[] array is less.

Approaches to Convert String to Char

Numerous approaches may be used to convert string to character. There are four ways to convert string std::string to char* in C++. The returned array should contain the same string sequence as the string object.

  • Approach-1: Using For Loop
  • Approach-2: Using  c_str() and strcpy() function. function
  • Approach-3: Using without the c_str() and strcpy() function.
  • Approach-4: Using Address Assignment

Lets dive in details for each approach.

Approach-1: Using For Loop

In c++, a string may be converted into a character using a for loop. To demonstrates this approach, an algorithm and c++  program is created which shown below:

Algorithm:

Step-1: Initial, a string will be created.

Step-2: Then, a character pointer is created. Length of string is determined.

Step-3: Assign each character of string to character array.

Step-4: Display character array and memory is deallocated.

C++ Code:

// C++ code to convert string to char using for loop
#include <iostream>
#include <string>
int main()
{
    std::string name = "JhonSmith"; //String object named string is created 
    char* chararray = new char[name.length() + 1]; // create a new array of chars 
    chararray[name.length()] = '\0';
    for (int i = 0; i < name.length(); i++) {
        chararray[i] = name[i];
    }
    std::cout << chararray;
    delete[] chararray;
    return 0;
}

Output:

JhonSmith

Code Explanation:

  • A string named ‘name’ is created and initialized by “JhonSmith”.
  • A character array Char* named chararray is created.
  • Length of string is determined and assigned each character of string to the character array.

Approach-2: Using c_str() with strcpy()

An alternative approach of converting string to characters is use of c_str() and strcpy() functions which enable programmers to copy symbols of string to character array. To demonstrates this approach, an algorithm and c++  program is created which shown below:

Algorithm:

Step-1: Initial, a string will be created.

Step-2: Then, a character pointer is created using c_str() function. Length of string is determined.

Step-3: Copy each character of string to character array using strcpy() function.

Step-4: Display character array and memory is deallocated.

Code:

// C++ code to convert string to char using c_str() with strcpy() function
#include <cstring>
#include <string>
#include <iostream>
 int main()
{
       std::string Address = "120,HillsTown";   // A string named Address is created and initialized 
     const int len = Address.length();
     char* charr = new char[len + 1];   // Here character array is created
     strcpy(charr, Address.c_str());    // Here,  the contents of the string is copied into char array
     for (int k = 0; k < len; k++)
    {
        std::cout << charr[k];      // It display character array
    }
       delete[] charr;                   // It deallocate memory allocated by character array
      return 0;
}

Output:

120,HillsTown

Code Explanation:

  • A string named ‘Address’ is created and initialized by “120,HillsTown”.
  • A character array Char* named charr is created.
  • Length of string is determined and copied  each character of string to the character array using strcpy() function.

Approach-3: Using c_str() without strcpy()

In c++, we may also convert string to character without using the c_str() and strcpy() function. use the standard algorithm std::copy. To demonstrates this approach, an algorithm and c++  program is created which shown below:

Algorithm:

Step-1: Initial, a string will be created.

Step-2: Then, a constant character pointer is created using c_str() function.

Step-3: Assign character of string to character array.

Step-4: Display character array.

Code:

// C++ code to convert string to char without using c_str() with strcpy() function
#include <cstring>
#include <string>
#include <iostream>

int main()
{
       std::string Occupation = "SelfEmployee";    // A string named Occupation is created and initialized
       const char* ocup = Occupation.c_str();     // Here c_str() function returns a const pointer to null
       std::cout << ocup;        // It display character of array
       return 0;
}

Output:

SelfEmployee

Code Explanation:

  • A string named ‘Occupation’ is created and initialized by “SelfEmployee”.
  • A constant character pointer  named ocup is created.
  • Each character of the string  is assigned to the character array.
  • Character array is printed.

Approach-4: Using Address Assignment

The C++ older version does not guarantee that memory allocated for std::string is contiguous. The goal is to transform the string into a continuous vector of characters. Then, by calling &str[0] or &*str.begin, we may obtain a pointer to the underlying character array ().

Algorithm:

Step-1: Initial, a string will be created.

Step-2: Then, a constant character pointer is created using the assigned address of the first character of the string.

Step-3: Display character array.

Code:

// C++ code to convert string to char without using c_str() with strcpy() function
#include <cstring>
#include <string>
#include <iostream>
int main()
{
    std::string Sentence = "This is C++ program to convert string to character"; // A string named Sentence is created and initialized
     char* chrr = &Sentence[0]; // Here, chrr is created and assign address of first character of string into it
         std::cout << chrr;   // It display character of array
          return 0;
}

Output:

This is C++ program to convert string to character

Code Explanation:

  • A string named ‘Sentence’ is created and initialized by “This is C++ program to convert string to character”.
  • A constant character pointer  named chrr is created.
  • Address of the first character of the string is assigned to the character array.
  • Character array is printed.

Best Approach- Using Address Assignment Approach

The best approach to convert a string to character is assigning the address of the first character of string into a constant character pointer. It is the best approach because:

  • Reduce Code Length: It offers reducing length of code by replacing numbers of lines.
  • Programmer Convenient: It is a short and very convenient way .
  • Efficient: This approach is considered as efficient in time complexity.

Sample problems related to String to Char

Sample Problem-1: Using Approach-1

Problem Definition: Suppose students’ full names are stored into a string. Another substring is supplied by the programmer. Write an algorithm and C++ program to find if a given substring exists in the string or not.    

Solution: An algorithm for this problem is represented in the following steps.

Algorithm:

Step-1: First create a string which stores the full name of the student.

Step-2: Then, substring is created to match in the given string 

Step-3: A character pointer is created for both string and substring.

Step-4: Length of string is determined. Check each character of substring in the given string.

Step-5: If substring is found then it displays that substring exists in the given string.

C++ Code:

// A C++ program  to check substring in the given string named student full name
#include <iostream>
#include <string>
int main()
{
    int f==0
    std::string StudentName = "JummyKopikar"; //StudentName String object is created 
    char* namearray = new char[StudentName.length() + 1]; //pointer character is created 
    namearray[ StudentName.length()] = '\0';
     std::string substr = "my"; //substr string object is created 
    char* suba = new char[substr.length() + 1]; //pointer character is created for the substring 
    for (int i = 0; i < StudentName.length(); i++) {
       namearray[i] =StudentName[i];
    }
   for (int i = 0; i < substr.length(); i++) {
       suba[i] =substr[i];
    }
   for(int j=0; j<substr.length();j++)
   { 
     for (int i = 0; i < StudentName.length(); i++) {
       if (suba[j] == namearray[i]) 
        {
        f=f+1
        break;
        } 
 }
if (f==substr.length())
{
  std::cout << “Substring is exists in the studentname string”;
 }
else
{
  std::cout << “Substring does not exists in the studentname string”;
 }
return 0;
}

Output:

Substring is exists in the studentname string

Code Explanation:

  • StudentName string is created using std::string that contain student full name
  • A substring named my is also created which is found in the student name string.
  • A substring found message is displayed.

Sample Problem-2: Using Approach-2

Problem Definition:  Consider a string which is created in the C++.  Write an algorithm and program to copy a string into another string.

Solution: An algorithm for this approach is represented in the following steps.

Algorithm:

Step-1: First string is created.

Step-2: C_STR() function will be used to create  character pointers. Length of string is determined.

Step-3: Copy contents of first string to second string  using strcpy() function.

Step-4: Display contents of the second string.

Code:

// C++ program to copy contents of one string into second string using c_str() with strcpy() function
#include <cstring>
#include <string>
#include <iostream>
 int main()
{
       std::string First = “It is first string”;   // A first string is created using std::string
     const int size = First.length();
     char* Second = new char[len + 1];   // Here second string array is created
     strcpy(Second, First.c_str());    // Here,  the contents of the first string is copied into second string
 for (int j = 0; j < len; j++)
    {
        std::cout << Second[j];      // It display contents of second string
    }
       delete[] Second;                   // It deallocate memory allocated by second string
      return 0;
}

Output:

It is first string

Code Explanation:

  • First string is created using std::string.
  • Second array using a pointer character array is created.
  • Copy  each character of the first string into the second string using strcpy() function.

Sample Problem-3:Using Approach-3

Problem Definition: Consider a C++ string that length is variable. Write an algorithm and C++ program to compute the length of the given string.   

Solution: An algorithm for this problem is represented in the following steps.

Algorithm:

Step-1:First, a string will be created.

Step-2: Compute length of the given string using string length function.

Step-3: Display length of the string.

Code:

// C++ Program to compute length of the given string
#include <iostream>
#include <string>
int main()
{
    std::string  Player = "Criastiona Ronaldo"; //Player string is created 
   stringlen=Player.length();
        std::cout << “The length of string is: ”<<stringlen;
    delete[] Player;
    return 0;
}

Output:

The length of string is:18

Code Explanation:

  • A string named ‘player’ is created.
  • The length of the player string is computed using length () function i.e. 18.
  • Length is displayed.

Sample Problem-4:Using Approach-4

Problem Definition: Consider a C++ string which is required to copy its content into another string without strcpy() function of C++ string. Write an algorithm and C++ program to copy the contents of the given string.   

Solution: An algorithm for this problem is represented in the following steps.

Algorithm:

Step-1: Initially, the first string is created.

Step-2: Assign the address of the first character of the string first using address (&) operator.

Step-3: Display the resulting string.

Code:

// C++ program to copy contents of first string into another without using strcpy()
#include <cstring>
#include <string>
#include <iostream>
int main()
{
    std::string FirstString = "C++ FirstString"; // FirstSting is created 
   char* SecondString = &FirstString[0]; // SecondString is created and assign address of first character of FirstString into this
         std::cout << SecondString;   // It display contents of SecondString
          return 0;
}

Output:

C++ FirstString

Code Explanation:

  • FirstString  is created and initialized by “ C++ FirstString”.
  • A SecondString is created.
  • Address of the first character of the FirstString is assigned to the SecondString using the address operator.
  • SecondString is printed.

Conclusion

C++ supports many ways to convert string to char using inbuilt functions and other methods. In this article, many approaches to convert a String  to Char were presented with an algorithm, C++ code, output and its explanation. Aim to conversion is  because string uses dynamic memory allocation but not in char.