Table of contents
1.
Introduction
2.
How to Convert a String to an Array Using the toCharArray() Method?
3.
How to Split a String Using the split() Method?
4.
How to Convert a String to an Array Using a StringTokenizer?
4.1.
Syntax of StringTokenizer
5.
Applications of StringTokenizer
6.
How to Convert Each Character in a String to an Array Element Manually?
7.
Comparison of the Different Methods 
8.
Why Should You Know How to Convert a String to an Array in Java?
9.
Frequently Asked Questions
9.1.
Can I convert a string to an array of integers or other data types?
9.2.
What happens if I use the `split()` method with an empty string as the delimiter?
9.3.
Are there any performance differences between the different methods of converting a string to an array?
10.
Conclusion
Last Updated: Nov 16, 2024
Easy

Convert String to Array in Java

Author Rinki Deka
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Strings and arrays are two of the most commonly used data types in every programming language, including Java. Strings store text data, while arrays hold collections of elements. In many situations, you may need to convert a string into an array to perform operations like sorting, searching, or manipulating individual characters. Java provides several ways to do this conversion. 

Convert String to Array in Java

In this article, we'll discuss different methods of converting a string to an array in Java. We'll explain how to use the toCharArray() method, split() method, StringTokenizer class and manually convert each character. 

How to Convert a String to an Array Using the toCharArray() Method?

The toCharArray() method is a built-in Java method that converts a string into a new character array. It returns an array of chars where each element represents a character from the original string, in the same order.

To use toCharArray(), simply call it on the string you want to convert. 

For example:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        String str = "Hello";
        char[] charArray = str.toCharArray();
        System.out.println(Arrays.toString(charArray));
    }
}
You can also try this code with Online Java Compiler
Run Code

 

Output:

[H, e, l, l, o]


In this code, we define a string `str` with the value "Hello". We then call `toCharArray()` on `str`, which returns a new char array containing the characters of the string. Finally, we print the contents of the array using `Arrays.toString()`.

The toCharArray() method is very simple and efficient for converting a string to a character array. It preserves the order of the characters and doesn't require any additional arguments.

How to Split a String Using the split() Method?

The split() method in Java splits a string into an array of substrings based on a specified delimiter. The delimiter can be a single character, a regular expression, or a fixed string.

Let’s look at the syntax of the split() method:

The split() method has two common variations:

1. `split(String regex)`: Splits the string based on the provided regular expression.
 

2. `split(String regex, int limit)`: Splits the string based on the regular expression, limiting the resulting array to a maximum of `limit` substrings.
 

For example : 

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        String str = "apple,banana,cherry";
        String[] fruits = str.split(",");
        System.out.println(Arrays.toString(fruits));
    }
}
You can also try this code with Online Java Compiler
Run Code


Output:

[apple, banana, cherry]


In this example, we have a string `str` containing a comma-separated list of fruits. We use the `split()` method with the delimiter "," to split the string into an array of substrings. The resulting array `fruits` contains each fruit as a separate element.

You can also specify a limit to control the maximum number of substrings in the resulting array. 

For example:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        String str = "apple,banana,cherry,date";
        String[] fruits = str.split(",", 3);
        System.out.println(Arrays.toString(fruits));
    }
}
You can also try this code with Online Java Compiler
Run Code

 

Output:

[apple, banana, cherry,date]


In this case, we set the limit to 3, so the `split()` method splits the string into a maximum of three substrings. The last substring contains the remaining part of the string that wasn't split.

When this can be used: The split() method is useful when you have a string with a known delimiter and want to extract the individual parts into an array. It provides flexibility through regular expressions and the ability to limit the number of resulting substrings.

How to Convert a String to an Array Using a StringTokenizer?

The StringTokenizer class in Java is another way to split a string into an array of substrings, or tokens, based on a specified delimiter. It provides a simple and efficient way to tokenize a string.

Syntax of StringTokenizer

To use StringTokenizer, you must create an instance of the StringTokenizer class by passing the string and the delimiter as arguments. 

For example:

import java.util.Arrays;
import java.util.StringTokenizer;

public class Main {
    public static void main(String[] args) {
        String str = "apple,banana,cherry";
        StringTokenizer tokenizer = new StringTokenizer(str, ",");
        String[] fruits = new String[tokenizer.countTokens()];
        int index = 0;
        while (tokenizer.hasMoreTokens()) {
            fruits[index++] = tokenizer.nextToken();
        }
        System.out.println(Arrays.toString(fruits));
    }
}
You can also try this code with Online Java Compiler
Run Code

 

Output:

[apple, banana, cherry]


In this code, we create a StringTokenizer instance called `tokenizer` by passing the string `str` and the delimiter ",". We then create a string array `fruits` with a size equal to the number of tokens in the tokenizer, which we obtain using the `countTokens()` method.

We iterate over the tokenizer using a while loop and the `hasMoreTokens()` method, which checks if there are more tokens available. Inside the loop, we retrieve each token using the `nextToken()` method and store it in the `fruits` array.

Finally, we print the contents of the `fruits` array using `Arrays.toString()`.

Applications of StringTokenizer

StringTokenizer is very useful when you have a string with a specific delimiter and you want to extract the individual tokens. Some common applications where this can be useful are:

  • Parsing comma-separated values (CSV) data
     
  • Splitting a sentence into individual words
     
  • Extracting data from a formatted string

Note: StringTokenizer provides a simple and efficient way to tokenize a string without the need for regular expressions.

How to Convert Each Character in a String to an Array Element Manually?

If you want more control over the conversion process or need to perform custom operations on each character, you can manually convert each character in a string to an array element. Let’s see how you can do it:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        String str = "Hello";
        int length = str.length();
        char[] charArray = new char[length];
        for (int i = 0; i < length; i++) {
            charArray[i] = str.charAt(i);
        }
        System.out.println(Arrays.toString(charArray));
    }
}
You can also try this code with Online Java Compiler
Run Code


Output:

[H, e, l, l, o]


In this code, we start by getting the length of the string using the `length()` method. We then create a character array `charArray` with a size equal to the length of the string.

Next, we use a for loop to iterate over each character in the string. We use the `charAt()` method to retrieve the character at each index `i` & assign it to the corresponding element in the `charArray`.

Finally, we print the contents of the `charArray` using `Arrays.toString()`.

This manual approach gives you complete control over the conversion process. You can perform additional operations or transformations on each character before adding it to the array.

For example, let's say you want to convert each character to uppercase before adding it to the array. You can modify the code like this:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        String str = "Hello";
        int length = str.length();
        char[] charArray = new char[length];
        for (int i = 0; i < length; i++) {
            charArray[i] = Character.toUpperCase(str.charAt(i));
        }
        System.out.println(Arrays.toString(charArray));
    }
}
You can also try this code with Online Java Compiler
Run Code


Output:

[H, E, L, L, O]


In this modified code, we use the `Character.toUpperCase()` method to convert each character to uppercase before assigning it to the `charArray`.

Note: The manual approach provides flexibility when you need to perform custom operations on each character during the conversion process.

Comparison of the Different Methods 

MethodDescriptionWhen to Use
toCharArray()The toCharArray() method is a built-in Java method that converts a string into a new character array. It returns an array of chars where each element represents a character from the original string, in the same order.Use toCharArray() when you need to convert a string to a character array and preserve the order of the characters. It is straightforward and efficient for simple string-to-array conversions.
split()The split() method in Java is used to split a string into an array of substrings based on a specified delimiter. The delimiter can be a single character, a regular expression, or a fixed string. You can also specify a limit to control the maximum number of substrings in the resulting array.Use split() when you have a string with a known delimiter and want to extract the individual parts into an array. It provides flexibility through regular expressions and the ability to limit the number of resulting substrings.
StringTokenizerThe StringTokenizer class in Java is another way to split a string into an array of substrings, or tokens, based on a specified delimiter. It provides a simple and efficient way to tokenize a string without the need for regular expressions.Use StringTokenizer when you have a string with a specific delimiter and want to extract the individual tokens. It is particularly useful for parsing comma-separated values (CSV) data, splitting a sentence into individual words, or extracting data from a formatted string.
Manual ConversionIf you want more control over the conversion process or need to perform custom operations on each character, you can manually convert each character in a string to an array element using a loop and the charAt() method. This approach gives you complete control over the conversion process and allows additional operations on each character.Use manual conversion when you need to perform custom operations on each character during the conversion process. It provides flexibility and allows you to modify or transform the characters as needed before adding them to the array.

Why Should You Know How to Convert a String to an Array in Java?

1. Text Processing: When working with text data, you often need to process & manipulate individual characters or substrings. Converting a string to an array allows you to access & operate on each character or substring separately, making text processing tasks easier & more efficient.
 

2. Algorithms & Data Structures: Many algorithms & data structures, such as sorting & searching, are designed to work with arrays. By converting a string to an array, you can apply these algorithms & data structures to the individual elements of the string.
 

3. Parsing & Tokenization: Converting a string to an array is often the first step in parsing or tokenizing data. Whether you're working with comma-separated values (CSV), JSON, or any other formatted data, splitting the string into an array of tokens makes it easier to extract & process the individual elements.
 

4. Regex & Pattern Matching: Regular expressions (regex) are powerful tools for pattern matching and string manipulation. When you convert a string to an array, you can apply regex patterns to individual elements of the array, allowing for more targeted and precise pattern matching.
 

5. Data Transformation: Converting a string to an array opens up possibilities for data transformation. You can modify, filter, or transform the individual elements of the array before joining them back into a string. This is useful when you need to perform operations like case conversion, substring extraction, or data cleaning.

Frequently Asked Questions

Can I convert a string to an array of integers or other data types?

Yes, you can use the `split()` method to split the string into an array of substrings, and then parse each substring into the desired data type using methods like `Integer.parseInt()` or `Double.parseDouble()`.

What happens if I use the `split()` method with an empty string as the delimiter?

If you use an empty string as the delimiter in the `split()` method, it will split the string into an array of individual characters, effectively achieving the same result as using the `toCharArray()` method.

Are there any performance differences between the different methods of converting a string to an array?

The `toCharArray()` method is generally the most efficient for converting a string to a character array. The `split()` method and `StringTokenizer` are more suitable when you need to split the string based on a specific delimiter. Manual conversion provides the most control but may be slower for large strings.

Conclusion

In this article, we discussed different methods of converting a string to an array in Java. We learned how to use the `toCharArray()` method, `split()` method, `StringTokenizer` class, and manual conversion. Each approach has its advantages and use cases, so you have to choose the most suitable method based on your specific requirements. 

You can also check out our other blogs on Code360.

Live masterclass