Table of contents
1.
Introduction
2.
Converting Array To String in C++ 
2.1.
Method 1: Applying the brute force approach
2.2.
Method 2: Using std::string
2.3.
Method 3: Overloaded Operator
3.
Converting Array To String in Java
3.1.
Method 1: Arrays.toString() method
3.2.
Method 2: String.join() method
4.
Converting Array To String in Python
4.1.
Method 1: Iterate over List
4.2.
Method 2: Use join() function
4.3.
Method 3: Using list comprehension
4.4.
Method 4: Use of map() 
5.
Converting Array To String in PHP
5.1.
Method 1: Use the implode() function
5.2.
Method 2: Use of the json_encode() function
6.
Converting Array To String in C#
6.1.
Method 1: Overloaded constructor
6.2.
Method 2: Using String.Join() Method
6.3.
Method 3: Using the String.concat() method
7.
Frequently Asked Questions
7.1.
Are string and array the same?
7.2.
How do you access a string array?
7.3.
Is string a function in C++?
7.4.
How to convert array of string to character?
7.5.
How to convert array to string without commas?
8.
Conclusion
Last Updated: Sep 29, 2024
Easy

How To Convert Array To String?

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

string is a contiguous sequence of characters in computer programming, either as a literal constant or variable. Additionally, strings must be stored sequentially because it is a contiguous sequence of characters; And the best data structure for this is an array using several character encodings.

How To Convert Array To String?

Remember, “The string is not a data structure. But it is a data type.” In some languages, it is available as primitive types and in others as composite types.

A string is another popular topic in programming job interviews. Furthermore, I have never participated in a coding interview where no string-based questions were asked.

So today, through this article, you will learn to convert array to string in C++, JAVA, PYTHON, PHP, C#.

Converting Array To String in C++ 

A character array is simply a collection of characters that is terminated by a null character (‘/0’). In contrast, a string is a class that defines objects as a stream of characters.

C++  has in its definition a method to represent a sequence of characters as an object of std::string class. 

The std::string in C++ has many in-built features, making implementation a whole lot simpler than dealing with a character array. Therefore, it’d often be more straightforward to work if we convert a character array to a string.

Let’s move on to explore various methods in C++ to convert array to string:

Method 1: Applying the brute force approach

Approach:

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

Implementation:

#include <bits/stdc++.h>
using namespace std;

//Function converts character array
// to string and returns it

string convertToString(char* array, int size)
{
	int i;
	string result_string = "";
	for (i = 0; i < size; i++) 
           {
	result_string = result_string + array[i]; //concatenation
	}
	return result_string;
}

// Main code
int main()
{
	char array[] = { 'C', 'o', 'd', 'i',’n’,’g’,’N’,’i’,’n’,’j’,’a’,’s’ };
	int  size = sizeof(array) / sizeof(char);
	string result_string = convertToString(array,size);
	cout << result_string << endl;
	return 0;
}
You can also try this code with Online C++ Compiler
Run Code


Output:

CodingNinjas
You can also try this code with Online C++ Compiler
Run Code

Method 2: Using std::string

Std::string class has a built-in constructor that can do all the work for us. This constructor takes a null-terminated string as input. However, we can only use this method during string declaration, and we cannot use it again on the exact string because it uses a constructor that is only called when we declare the string.

Approach:

  • Get the character array and its size.
  • Declare a string (i.e. String class object) and pass the character array as a parameter to the constructor.
  • Use syntax: string string_name (character_array_name);
  • Return the string.
     

Implementation:

#include <bits/stdc++.h>
using namespace std;
// Main code
int main()
{

char array[] = { 'C', 'o', 'd', 'i', 'n', 'g', 'N', 'i', 'n', 'j', 'a', 's'};
//Using string() function
string s(array);
//print Output
cout << s << endl;
return 0;
}
You can also try this code with Online C++ Compiler
Run Code


Output:

CodingNinjas
You can also try this code with Online C++ Compiler
Run Code

 

Also see, Morris Traversal for Inorder and Rabin Karp Algorithm

Method 3: Overloaded Operator

Another option is to use the overloaded ‘=’ operator, which is also available in C++ std::string.

Approach: 

  • Get the character array and its size.
  • Declare a string.
  • Use the overloaded ‘=’ operator to assign the characters in the character array to the string.
  • Return the string.
     

Implementation:

#include <bits/stdc++.h>
using namespace std;
// Main code
int main()
{
char array[] = { 'C', 'o', 'd', 'i', 'n', 'g', 'N', 'i', 'n', 'j', 'a', 's' };
string result_string = array;//operator overloading
cout << result_string << endl;
return 0;
}
You can also try this code with Online C++ Compiler
Run Code


Output:

CodingNinjas
You can also try this code with Online C++ Compiler
Run Code

Converting Array To String in Java

Strings in Java consist of a list of array elements enclosed in square brackets ([]). However, in the character array, adjacent elements are separated by the characters “,”  (a comma followed by space). If the array is empty, “Null” is returned.

In some cases, you need to convert an array to a string, but unfortunately, there is no direct way to achieve that in Java. Since arrays are considered objects in Java, you might be wondering why you can’t use the toString() method. If you try to call toString() on an array, it gives some error C@15db9742, which is not human-comprehensible.

Unlike C / C ++ strings, Java strings are immutable, meaning they cannot be changed once created. Yes, you can use some methods to manipulate strings. But these will not change the underlying data structure of the string; they will create a new copy.

Below are several methods for converting arrays to strings in Java: 

Method 1: Arrays.toString() method

The Arrays.toString() method is used to return the string representation of the specified array. All array elements are separated by “,” and enclosed in parentheses “[]”.

Let’s see how to generate a single string in an array of strings using the Arrays.toString () method!

Implementation:

import java.util.Arrays;

public class Main 
{
    public static void  main(String[] args) 
    {
        // Array of Strings
        String[] data2 = {"Hey", "How", "are", "you", "?"};
        //Use of Arrays.toString Method
        String joinedstr2 = Arrays.toString(data2);
        System.out.println(joinedstr2);
    }
}
You can also try this code with Online Java Compiler
Run Code


Output:

[Hey , How , are , you, ?]
You can also try this code with Online Java Compiler
Run Code

Method 2: String.join() method

This combines an array of strings belonging to the String class to create a single string instance. Returns a new string consisting of CharSequence elements concatenated using the specified delimiter.

Implementation:

import java.util.Arrays;
import java.util.List;

public class Main 
{
    public static void  main(String[] args) 
    {
        // Array of Strings
        String[] data = {"Array", "Into", "String","In", "Java", "Example"};
        String joinedstr = String.join(" ", data);
        System.out.println(joinedstr);
        CharSequence[] vowels  = {"h", "e", "l", "l", "o"};
        String joinedvowels = String.join(",", vowels);
        System.out.println(joinedvowels);
        List<String> strList = Arrays.asList("code", "with", "us");
        String joinedString = String.join(", ", strList);
        System.out.println(joinedString);
    }
}
You can also try this code with Online Java Compiler
Run Code


Output:

Array Into String In Java Example 
h,e,l,l,o
code, with, us
You can also try this code with Online Java Compiler
Run Code

Converting Array To String in Python

A variety of situations can occur when given a list and converting it to a string -for example, converting from a list of strings or a list of integers to a string.

Input: arr- [“Array”,” to”, ” string”,” conversion”,” example”]

Output: Array to string conversion example

Method 1: Iterate over List

We will iterate over a list of characters, concatenating elements at all indices of an empty string.

Implementation:

# Python program to convert a list to string
# Function to convert
def listToString(arr):
	# initialize an empty string
	str1 = ""
	# traverse in the string
	for ele in arr:
		str1 += ele //concatenation
	# return string
	return str1
		
arr =[“Array”,” to”, ” string”,” conversion”,” example”]
print(listToString(arr))
You can also try this code with Online Python Compiler
Run Code


Output:

Array to string conversion example
You can also try this code with Online Python Compiler
Run Code

Method 2: Use join() function

Python is also known and “easy to work” because of its in-built functions. For example, here join() inbuilt method can be used to convert string array to string.

Implementation:

# Python program to convert a list
# to string using join() function
def listToString(arr):
	# initialize an empty string
	str1 = " "
	# return string
	return (str1.join(arr))
		
arr =[“Array”,” to”, ” string”,” conversion”,” example”]
print(listToString(arr))
You can also try this code with Online Python Compiler
Run Code


Output:

Array to string conversion example
You can also try this code with Online Python Compiler
Run Code

 

But what if the list contains both strings and integers? 

In this case, the above code will not work. This is because array elements must be converted to a string when concatenated with the resultant string.

Method 3: Using list comprehension

  • List comprehensions are often described as more Pythonic than loops or map().
  • List comprehensions provide a concise way to create lists.
     

Implementation:

# Python program to convert a list
# to string using list comprehension
s = ['We', 'have', 4, 'mangoes', 'and', 18, 'bananas']
# using list comprehension
listToStr = ' '.join([str(elem) for elem in s])
print(listToStr)
You can also try this code with Online Python Compiler
Run Code


Output:

We want 4 mangoes and 18 bananas
You can also try this code with Online Python Compiler
Run Code

Method 4: Use of map() 

Use map() method for converting elements within the list to string to a specific list of iterators.

Implementation:

# Python program to convert a list
# to string using list comprehension
s = ['We', 'have', 4, 'mangoes', 'and', 18, 'bananas']
# using map() method
listToStr = ' '.join(map(str, s))
print(listToStr)
You can also try this code with Online Python Compiler
Run Code


Output:

We want 4 mangoes and 18 bananas
You can also try this code with Online Python Compiler
Run Code

Converting Array To String in PHP

In PHP also, Strings are sequences of characters, like “String is a data-type and PHP supports string operations”.

Let’s check some methods to convert an array of characters to a string in PHP.

Method 1: Use the implode() function

The implode() method is a PHP built-in function used to combine the elements of an array. The implode() method is a PHP alias. It is a join() function and works exactly like the join() function.

Implementation:

<?php
#Declare an array
$arr = array("Welcome","to", "Coding","Ninjas","Blogs");
#Converting array elements into
#strings using implode function
echo implode(" ",$arr);
?>
You can also try this code with Online PHP Compiler
Run Code


Output:

Welcome to Coding Ninjas Blogs
You can also try this code with Online PHP Compiler
Run Code

Method 2: Use of the json_encode() function

The json_encode() function is a PHP built-in function used to convert an array or object in PHP to a JSON representation.

Implementation:

<?php
#Declare multi-dimensional array
$value array("name"=>"Code",array("email"=>"abc@cn.com","mobile"=>"XXXXXXXXXX"));
#Use json_encode() function
$json = json_encode($value);
#Display the output
echo($json);
?>
You can also try this code with Online PHP Compiler
Run Code

 

Output:

{"name":"Code","0":{"email":"abc@cn.com","mobile":"XXXXXXXXXX"}}
You can also try this code with Online PHP Compiler
Run Code

Converting Array To String in C#

The user has given the input as a character array named arr. The challenge is to convert the character array array to a string using the C# programming language.

Method 1: Overloaded constructor

Use the string() method. The String class has several overloaded constructors that accept a character or byte array so that it can be used to extract from the character array to create the new string.

Implementation:

using System;
using System.Text;

public class Find{
	static void Main(string[] args)
	{
		// input character array
		char[] arr = {'C', 'o', 'd', 'i', 'n', 'g'};
		
		// convert character array to string
		string str = new string(arr);
		
		// printing output
		Console.WriteLine(str);
	}
}


Output:

Coding

Method 2: Using String.Join() Method

This method is used to concatenate the members of the specified array elements, using the specified separator between each element. 

Thus String.Join() method can be used to create a new string from the character array.

Implementation:

using System;
using System.Text;
 
public class Find{
    static void Main(string[] args)
	{
		// input character array
		char[] arr = {'C', 'o', 'd', 'i', 'n', 'g'};
		// using String.Join() 
		string result_string = String.Join("", arr);
		// printing output
		Console.WriteLine(result_string);
	}
}


Output:

Coding

Method 3: Using the String.concat() method

This method connects one or more string instances or the string representing the value of one or more object instances. So it can be used to create a new string from an array of characters.

Implementation:

using System;
using System.Text;

public class Find
{
    static void Main(string[] args)
	{
		// input character array
		char[] arr = {'C', 'o', 'd', 'i', 'n', 'g'};
		// function calling for converting
		string result_string = String.Concat(arr);
		// printing output
		Console.WriteLine(result_string);
	}
}

 

Output:

Coding

 

Must Read Array of Objects in Java

Frequently Asked Questions

Are string and array the same?

An array is a collection of like-type variables, whereas a string is a sequence of characters represented by a single data type. An array is a data structure where a string is a data type.

How do you access a string array?

You can use the index to access the values ​​in the array and place the index of the element in square brackets along with the name of the array.

Is string a function in C++?

In C++, the string is an object of the std::string class that represents a sequence of characters.

How to convert array of string to character?

To convert an array of strings to characters, loop through each string in the array, then split each string into its individual characters. Append these characters to a new array or list, depending on the programming language.

How to convert array to string without commas?

To convert an array to a string without commas, use a method like join() in Python or JavaScript, and pass an empty string "" as the delimiter. This ensures the array elements are concatenated without any commas or spaces.

Conclusion

Converting an array to a string is a crucial task in programming, enabling easy data formatting and presentation. Whether you're preparing data for output, storage, or transmission, the ability to seamlessly transform arrays into strings simplifies the process.

Check out the following problems:


You can explore and try as many problems as possible on our platform Code360 created by creative minds, which provides you with hassle-free, adaptive, and excelling online courses, practice questions, blogs, interview experiences, and everything you need; to become the perfect candidate for your dream company!

Live masterclass