Array to String

In this article, we will discuss the method to convert an array to string. We will discuss the conversion of character array to string using iteration and some language-specific conversions for converting arrays to strings. So, let’s get started.

Convert a Character Array to String

Consider that we have a character array as shown below.

We have to convert this character array to string. So, how do we do that?

Let us take an empty string str and pointer i on the 0 index of the array as shown below.

Now, we will append the character that is present on the ith index of the array to this string str and will increment the pointer i to the next index as shown below.

Similarly, we will do this for index 1 as shown below.

Similarly, we can traverse the rest of the array till the index reaches out of the bounds of the array. We keep on appending the character present at the ith index of the array to the string str and we get our answer.

So, this is a very simple and basic method to convert an array to string. The C++, Java, and Python programs for the method discussed above are shown below.

#include<bits/stdc++.h>
using namespace std;
int main()
{
    char arr[] = {'a','e','i','o','u'};
    string str = "";
    int n = sizeof(arr)/sizeof(char);
    
    for(int i=0;i<n;i++) {
        str += arr[i];
    }
    
    cout<<str;
}
import java.util.*;

public class Main {
    
    public static String convertArrayToString(char[] arr) {
        StringBuilder sb = new StringBuilder("");
        for(int i=0;i<arr.length;i++) {
            sb.append(arr[i]);
        }
        
        return sb.toString();
    }
    
    public static void main(String[] args) {
        char[] arr = {'a','e','i','o','u'};
        String str = convertArrayToString(arr);
        System.out.println(str);
    }
}
def main():
    arr = ['a','e','i','o','u']
    string = ""
    
    for ch in arr:
        string += ch
    
    print(string)

if __name__ == '__main__':
    main()

Time Complexity: In Java, we have used a StringBuilder instead of using a String for appending characters as a String in Java is immutable and interning cause the operation of adding a character to a string of length N being O(N). So, we use a StringBuilder where adding a character to a string is an O(1) operation.
Since here, we are just traversing the string and adding one character to it at a time which is an O(1) operation and this is done N time (since N is the length of the array), so, the time complexity is O(N).

Space Complexity (Auxiliary Space): Since we have not used any extra space the space complexity is O(1).

So, this is a generic method that is used in any programming language to convert a character array to string. Now, let us see some language-specific methods to convert an array to string.

Convert Any Array to String in Java – Arrays.toString() Method

In Java, the Arrays.toString() method is used to convert any array to a string. The array can be an integer array or a character array or a boolean array, etc. The program to convert an array to string using Arrays.toString() in Java is shonw below.

import java.util.*;

public class Main {
    public static void main(String[] args) {
        char[] arr1 = {'a','e','i','o','u'};
        System.out.println(Arrays.toString(arr1));
        
        int[] arr2 = {1,2,3,4,5};
        System.out.println(Arrays.toString(arr2));
        
        boolean[] arr3 = {true,true,false,true};
        System.out.println(Arrays.toString(arr3));
        
        String[] arr4 = {"Follow","PrepBytes","for","more","such","content"};
        System.out.println(Arrays.toString(arr4));
    }
}

Convert Character Array to String in Java – StringBuilder.append(char [ ] array )

In Java, we can convert a character array to string by appending the character array directly to a stringbuilder and then calling the toString() method of the StringBuilder class. This is shown in the program below.

import java.util.*;

public class Main {
    public static void main(String[] args) {
        char[] arr = {'a','e','i','o','u'};
        StringBuilder sb = new StringBuilder("");
        sb.append(arr);
        System.out.println(sb.toString());
    }
}

Convert a String Array to String in Python – Using join() method

What if we have an array of strings and we want to convert this array of string to one single string. Well, python provides us a method called join() using which we can achieve this. Consider the array shown below.

Using the join method, we can convert this array to the following string.

The program for the same is shown below.

def solve(arr):
    s = " "; #delimeter that joins multiple strings of the array together
#     So, every string of the array arr will have this delimeter between them
    return s.join(arr)

def main():
    arr = ['PrepBytes','offers','excellent','courses']
    print(solve(arr))
    
if __name__ == '__main__':
    main()

As discussed above, this program will work if the array is an array of strings. What if the array contains both strings and integers? Let us look at the method to solve such a problem.

Python Program to Convert any Array to String – List Comprehension Method

The list comprehension uses join() method to join the elements of a list together using a delimiter, however, first converting each individual element to a string. This is shown below.

def solve(arr):
    return (' '.join([str(ele) for ele in arr]))

def main():
    arr = ['I','have','solved',350,'DSA','questions','out','of',500]
    print(solve(arr))
    
if __name__ == '__main__':
    main()

So, there are some more methods in Python too for converting an array to string. However, we can do most of the work with the methods discussed above. Let us now move to study some C++ methods to convert array to string.

Convert Character Array to String in C++ – Using the String Constructor

We can directly convert a character array to string using the string class constructor in C++. It automatically terminates the character array with a null ‘\0’ character to convert it into a string. This is shown in the program below.

#include <bits/stdc++.h>
using namespace std;
string convertToString(char* a)
{
    string s(a);
    return s;
}

int main()
{
    char a[] = { 'a', 'e', 'i', 'o', 'u' };

    string s_a = convertToString(a);

    cout << s_a << endl;

    return 0;
}

Conclusion
So, we have seen multiple methods to convert an array to string in C++, Python and Java. We also saw the default method of traversing and converting an array to string in all the 3 languages. So, with this, we come to an end of our discussion on the topic array to string. We hope that you understood the concepts and enjoyed the discussion. We hope to see you again soon at PrepBytes.

Let us now answer some Frequently Asked Questions.

Frequently Asked Questions

1. Why do we need to convert character arrays to strings? Can’t we work with character arrays only?
We can work with character arrays to some extent but not completely. Strings provide us the flexibility of increasing or trimming their length as and when required. However, arrays offer a rigid approach to this of maintaining a fixed size. So, it is mostly convinient to use strings instead of using character arrays in the operations involving strings.

2. Why are StringBuilders used in Java instead of Strings?
Strings are immutable in Java. When we add a character to a string, a new string is formed that copies the previous string and the character is then inserted in that new string. This means every time we add a character in a string, the entire string of length N is copied once. So, adding a character in a string is an O(N) operation in Java while it is an O(1) operation for strings in other programming languages. StringBuilder in Java is however similar to strings in other languages and adding a character to it is O(1) operation. Hence, we use StringBuilders instead of strings in Java more frequently.

3. Is there any inbuilt method to convert an array to string?
Most of the languages have inbuilt methods for converting arrays to strings. We saw some inbuilt methods in Java, C++ and Python in this article. So, yes, there are inbuilt methods to convert an array to string in most of the programming languages.

Leave a Reply

Your email address will not be published. Required fields are marked *