Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Convert String to Array

Last Updated on November 1, 2023 by Ankit Kochar

Java, a programming language, relies heavily on two fundamental data types – strings and arrays. Strings are employed to encapsulate textual data, while arrays serve as containers for storing and managing collections of information. Occasionally, the need arises to transform a string into an array, facilitating the manipulation of data in an alternative format. This operation is commonly referred to as "converting a string to an array" and is considered a fundamental skill for any Java developer.
Here we will discuss how to convert string to array and methods and approaches that how we can convert string to array in Java Since Strings are immutable in Java, changing the value of String results in the creation of a new String object rather than changing the value of the already-existing String object. The Java String class can be imported from Java.lang package.

A Java array is a construct composed of elements sharing a uniform data type, and these elements are stored contiguously in memory. It’s important to note that Java does not permit the modification of an array’s size, thus, an array is presumed to have a predetermined and unalterable number of elements.
We’ll go through Java’s character and string arrays in this tutorial.
In Java, a string is an object that represents a group of characters. Because Java Strings are immutable, their value cannot be modified after they are formed.
A straightforward for loop or the toCharArray() method can be used to convert a String to a char array.
In Java, a string array is a collection of strings. Java arrays have a defined length. Any of the following methods, such as String.split(), Pattern.split(), String[] {} and toArray(), can be used to transform a String to an array.

Convert String to Array of Character in Java

In Java, there are two ways to transform a String object into a character array:

1. Naive Approach To Convert String to Array Of Character

Here we have the naive approach which convert string to array:

A normal for-loop is used to read every character in the string and assign each one individually to a Character array.

Algorithm which convert string to array using a naive approach:

  1. Get the string
  2. The string’s length should match the size of the character array you create.
  3. Traversing the string copies the character at the ith place to the ith index of the array.
  4. Return the array of characters or carry out the operation on it.

Code Implementation

import java.util.*;

class StringtoCharArray {

  public static void main(String args[]) {
    String str = "PrepBytes"; // Given String

    // Creating array of string length
    char[] arr = new char[str.length()];

    // Copy character by character into array
    for (int i = 0; i < str.length(); i++) {
      arr[i] = str.charAt(i);
    }

    // Printing the character array
    for (char x : arr) {
      System.out.println(x);
    }
  }
}

Output:

P
r
e
p
B
y
t
e
s

2. Using toCharArray() Method To Convert String To Array of Character

We can employ the toCharArray() function to transform a string into a char array.

Algorithm which convert String to Array

  1. Get the string
  2. The character array that the toCharArray() method returns should be placed in a character array.
  3. Return the character array or use it to perform an action.

Code Implementation

import java.util.*;

class StringtoCharArray {

  public static void main(String args[])
  {

    String str = "PrepBytes";

    // Call the toCharArray() method
        // Store the result in a char array
    char[] arr = str.toCharArray();

    // Printing the character array
    for (char x : arr)
    {
      System.out.println(x);
    }
  }
}

Output:

P
r
e
p
B
y
t
e
s

Convert String To Array of Strings in Java

In this section, we’ll learn how to create an array of strings from a string in Java.
There are four ways to Convert String To Array of Strings in Java:

  • Using String.split() Method
  • Using Pattern.split() Method
  • Using String[ ] Approach
  • Using toArray() Method

So above these are the four ways to convert string to array.

Using String.split() Method To Convert String To Array Of Strings

Using the given delimiter (whitespace or other symbols), the String.split() function divides a string into separate strings . These objects can be kept in a string array directly.

Example 1: Take a look at the example below, which demonstrates how to use Java’s String.split() function to transform a string to an array or to convert string to array

class StrintoStringArray {

  public static void main(String[] args) {
    // Declaring and initializing a string
    String str =
      "Learn Coding From PrepBytes";

    // Declaring an empty string array
    String[] arr = null;

    // Converting using String.split() method with whitespace as a delimiter
    arr = str.split(" ");

    // Printing the converted string array
    for (int i = 0; i < arr.length; i++) {
      System.out.println(arr[i]);
    }
  }
}

Output:

Learn
Coding
From
PrepBytes

Example 2: In the example below, we convert string to array in Java by using the # delimiter.

class StringtoStringArray {

  public static void main(String[] args) {
    // Declaring and initializing a string
    String str = "What#is#your#name ?";

    // Declaring an empty string array
    String[] arr = null;

    // Converting using String.split() method
    // with hash(#) as a delimiter
    arr = str.split("#");

    // Printing the converted string array
    for (int i = 0; i < arr.length; i++) {
      System.out.println(arr[i]);
    }
  }
}

Output:

What
is
your
name ?

Using Pattern.split() Method To Convert String To Array Of Strings

The Pattern.split() method divides a string into an array of strings by using a regular expression (pattern) as the delimiter.
As seen in the code below, we must import the Pattern class into our Java code before we can apply the technique. Complex regex expressions can be compiled using this Pattern class.

Example 1: A string will be divided into an array in the example below by using whitespace as the delimiter.

import java.util.regex.Pattern;

class PatternSpiltMethod {

  public static void main(String[] args) {
    // Declaring and initializing a string
    String str =
      "Pattern.split() method to convert a string to array in Java ";

    // Declaring an empty string array
    String[] arr = null;

    // Parsing white space as a parameter
    Pattern ptr = Pattern.compile(" ");

    // Storing the string elements in array after splitting
    arr = ptr.split(str);

    // Printing the converted string array
    for (int i = 0; i < arr.length; i++) {
      System.out.println(arr[i]);
    }
  }
}

Output:

Pattern.split()
method
to
convert
a
string
to
array
in
Java

Example 2: To divide a string into an array, we may also use any string or pattern as a delimiter. Here, the &d& delimiter has been utilized.

import java.util.regex.Pattern;

class PatternSpiltMethod {

  public static void main(String[] args) {
    // Declaring and initializing a string with a separator
    String str = "What&d&is&d&your&d&name ?";

    // Declaring an empty string array
    String[] strArray = null;

    // Splitting the string with delimiter as #a1
    String patternStr = "&d&";
    Pattern ptr = Pattern.compile(patternStr);

    // Storing the string elements in array after splitting
    strArray = ptr.split(str);

    // Printing the converted string array
    for (int i = 0; i < strArray.length; i++) {
      System.out.println(strArray[i]);
    }
  }
}

Output:

What
is
your
name ?

Using String[ ] Approach To Convert String To Array of Strings

By simply placing a string inside the curly brackets of String [] {}, we may transform a string to a string array. This conversion will result in the creation of a String array with just the input string as its single element.

Take a look at the example below, which demonstrates how to use Java’s String[] {} method to transform a string to an array.

import java.util.Arrays;

class StringtoStringArray {

  public static void main(String[] args) {
    // Declaring and initializing a string
    String str =
      "Using the String[] method to convert a string to array in Java";

    // Passing the string to String[] {}
    String[] arr = new String[] {str};

    // Printing the elements of the string array using a for loop
    for(String ch : arr) {
        System.out.println(ch);
    }
  }
}

Output

Using the String[] method to convert a string to array in Java

Using toArray() Method To Convert String To Array Of Strings

Java programmers can also convert a string to an array by using the toArray() method of the List class. It accepts a list of String objects as input and turns each one into a string array element.

Take a look at the example below, where we turned a list of strings into a string array.

import java.util.ArrayList;
import java.util.List;

class ListToStringArray {

  public static void main(String[] args) {
    // Creating a list of type string
    List<String> list = new ArrayList<String>();

    // Adding elements to list
    list.add("What");
    list.add("is");
    list.add("your");
    list.add("name ?");

    // Size of list
    int list_size = list.size();

    // Creating string array
    String[] arr = new String[list_size];

    // Converting to string array
    list.toArray(arr);

    // Printing the string array
    for (int i = 0; i < arr.length; i++) {
      System.out.println(arr[i]);
    }
  }
}

Output

What
is
your
name ?

Conclusion
Converting a string to an array is a common operation in Java programming. This process enables developers to manipulate and process textual data as arrays of characters, providing more flexibility and control. In this conclusion, we’ll summarize key points and address frequently asked questions related to converting a string to an array in Java.

Frequently Asked Questions related to Convert String to Array

Here we have FAQs on convert string to array in Java:

1. What is string to array conversion in Java?
String to array conversion is the process of converting a string data type to an array data type in Java. This process is commonly used in programming when we need to manipulate string data in an array format.

2. Can I convert a string to an array of integers or other data types?
Yes, you can convert a string to an array of other data types, such as integers or doubles, by parsing the string and populating an array with the parsed values. This is a common operation for tasks like reading and processing input data.

3. What if my string contains spaces or special characters?
When converting a string to an array of characters, spaces and special characters are preserved as individual elements in the character array. For other data types, handling spaces and special characters may require additional parsing and processing.

4. Is it possible to change the size of an array after converting a string?
No, in Java, the size of an array is fixed upon creation and cannot be changed. If you need a dynamic collection that can change in size, consider using data structures like ArrayList or LinkedList.

5. What are some practical use cases for converting a string to an array?
Converting a string to an array is useful for tasks like text processing, searching, sorting, and performing character-level operations. It is commonly employed in applications involving data analysis, text-based games, and parsing textual content.

Leave a Reply

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