How To Convert Array To String In Any Programming Languages?

How To Convert Array To String In Any Programming Languages?
How To Convert Array To String In Any Programming Languages?

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.

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

Note:  

However, an array of characters and a string are not the same. A string is an array of characters but ends with a special character `\0`known as null.

Secondly, C++, C#, and Java uses single and double quotes to distinguish between single characters and strings, respectively. Whereas JavaScript, Python and Swift do not differentiate between characters and strings but use single or double quotes to define literal strings.

Thirdly before you read this article, make sure you go through following blogs: Reserve a string in C and C++

Now let’s begin with one of the most popular programming languages of all time, C++.

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;
}

Output:
CodingNinjas

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;
}

Output:
CodingNinjas

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;
}

Output:
CodingNinjas

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);
    }
}

OUTPUT
 [Hey , How , are , you, ?]

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);
    }
}

OUTPUT

Array Into String In Java Example 
h,e,l,l,o
code, with, us

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

Output
Array to string conversion example

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

Output:
Array to string conversion example

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)

Output
We want 4 mangoes and 18 bananas

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)

Output
We want 4 mangoes and 18 bananas

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.

<?php
#Declare an array
$arr = array("Welcome","to", "Coding","Ninjas","Blogs");
#Converting array elements into
#strings using implode function
echo implode(" ",$arr);
?>

Output
Welcome to Coding Ninjas Blogs

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.

<?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);
?>

Output
{"name":"Code","0":{"email":"abc@cn.com","mobile":"XXXXXXXXXX"}}

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.

To accomplish this task, we have the following methods: 

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

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

Frequently Asked Questions

Can we convert the array to string in Java?

There are various methods to convert an Array to String in Java: Arrays. toString() method , String.join() method etc.

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 I turn an array into a string in Python?

To convert a list to a string, use Python List Comprehension and the join() function.

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.

Key Takeaways

This article explains several ways to convert an array into a string in C++, Java, Python, PHP, C#. For example, In Java: Arrays. toString() method , String.join() method.

Likewise, In Python: join(), list comprehension method etc.

To give you a clear understanding, we also gave the implementation of each method in their respective programming languages. We have finally reached the end of our article, but this is not the end of methods!!

Indeed, there are various additional methods other than what we have discussed above to convert Array to String in all programming languages.

You can explore and try as many problems as possible on our platform CodeStudio 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!

If you feel the need for expert guidance to learn more concepts, check out our DSA courses by starting your free trial today.

By Aanchal Tiwari

Exit mobile version