0% found this document useful (0 votes)
9 views

String to Array in Java – How to Convert Strings to Arrays

Uploaded by

jaganpj2002
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

String to Array in Java – How to Convert Strings to Arrays

Uploaded by

jaganpj2002
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Forum Donate

Support our charity and our mission. Donate to freeCodeCamp.org.

JULY 6, 2023 / #JAVA

String to Array in Java – How


to Convert Strings to Arrays

By Shittu Olumide

Being able to convert a string into an array can be quite helpful


when you're developing text-processing applications or working
with data.

A string in Java is a group of characters, whereas an array is a


collection of the same type of element. You may deconstruct a string
into its parts using the conversion process, then store those parts in
an array for further manipulation or analysis.
This article will give you a variety of Java techniques for convertingDonate
Forum
strings to arrays. As we examine several strategies, we'll discuss
Support our charity and our mission. Donate to freeCodeCamp.org.
their syntax, applications, benefits, and drawbacks. Knowing how to
use these methods will enable you to select the one that best suits
your programming requirements.

How to Convert a String to an


Array Using the toCharArray()
Method
The toCharArray() method is a built-in function in Java that allows
you to convert a string into a character array. This method is
available in the String class and provides a convenient way to
convert each character in a string into an element of an array.

Syntax and usage of the toCharArray()


method

public class StringToArrayExample {


public static void main(String[] args) {
String str = "Hello, World!";

// Convert the string to an array of characters


char[] charArray = str.toCharArray();

// Print the array elements


for (char c : charArray) {
System.out.println(c);
}
}
}

Explanation:
1. Declare a string variable str and assign the desired string to Donate
Forum
it.
Support our charity and our mission. Donate to freeCodeCamp.org.
2. Use the toCharArray() method on the string str to convert
it into an array of characters. This method splits the string
into individual characters and returns an array containing
those characters.

3. Store the resulting character array in the variable


charArray .

4. Iterate over the charArray using a for-each loop to print


each character individually.

Output:

H
e
l
l
o
,

W
o
r
l
d
!

Pros of using toCharArray() :

Simplicity: The toCharArray() method provides a


straightforward way to convert a string to a character array
with just a single method call.

Readability: The resulting character array can be easily


manipulated, processed, or iterated over using loops.
Immutable strings: Since strings in Java are immutable,
Forum Donate
converting them to a character array can be useful when you
Support our charity and our mission. Donate to freeCodeCamp.org.
need to modify individual characters.

Cons of using toCharArray() :

Memory overhead: The toCharArray() method creates a


new character array, which requires additional memory. This
can be a concern if you are working with large strings.

Performance: Creating a new character array and copying


the characters can introduce some performance overhead
compared to other methods, especially for long strings.

How to Split a String Using the


split() Method
The split() method in Java is a convenient way to split a string
into an array of substrings based on a specified delimiter. It is a
widely used method for converting a string to an array in Java.

Syntax and usage of the split() method:


The split() method is available in the String class in Java and has
the following syntax:

String[] split(String delimiter)

The method takes a delimiter as an argument, which determines the


points at which the string should be split. The delimiter can be a
regular expression or a simple string.
Example code demonstrating the conversion using split()
Forum : Donate

Support our charity and our mission. Donate to freeCodeCamp.org.

string = "Hello,World,How,Are,You?"
delimiter = ","

split_string = string.split(delimiter)
print(split_string)

Explanation:

1. We define a string variable called string that contains the


text we want to split: "Hello,World,How,Are,You?".

2. We specify the delimiter we want to use for splitting the


string, which is a comma ( , ), and assign it to the variable
delimiter .

3. We use the split() method on the string variable,


passing the delimiter as an argument. This splits the string
into substrings wherever the delimiter is found.

4. The split() method returns a list of the substrings, which


we assign to the variable split_string .

5. Finally, we print the split_string list to see the output.

Output:

['Hello', 'World', 'How', 'Are', 'You?']

Pros of using split() :

Convenient and easy to use.


Allows splitting a string based on a specified delimiter.
Forum Donate

Supports
Support regular
our charityexpressions as delimiters,
and our mission. providing flexible
Donate to freeCodeCamp.org.
splitting options.

Cons of using split() :

If the delimiter is not found in the string, the original string is


returned as a single element in the resulting array.

Regular expressions can be complex to handle, and incorrect


usage may lead to unexpected results.

Splitting a large string using a complex regular expression


can be computationally expensive.

How to Convert a String to an


Array Using a StringTokenizer
The StringTokenizer class in Java is a legacy class that provides a
convenient way to tokenize or split a string into individual tokens. It
is commonly used to convert a string to an array by splitting it based
on a specified delimiter.

Syntax and Usage of StringTokenizer


To use StringTokenizer, you need to follow these steps:

First, create an instance of the StringTokenizer class, passing the


string and delimiter as parameters:

StringTokenizer tokenizer = new StringTokenizer(inputString, delimiter)

 
Example code: Forum Donate

Support our charity and our mission. Donate to freeCodeCamp.org.

import java.util.StringTokenizer;

public class StringToArrayExample {


public static void main(String[] args) {
String inputString = "Hello,World,How,Are,You?";

// Creating a StringTokenizer object with delimiter ","


StringTokenizer tokenizer = new StringTokenizer(inputString, ",

int tokenCount = tokenizer.countTokens();


String[] stringArray = new String[tokenCount];

// Converting each token to array elements


for (int i = 0; i < tokenCount; i++) {
stringArray[i] = tokenizer.nextToken();
}

// Printing the output array


for (String element : stringArray) {
System.out.println(element);
}
}
}

**Explanation**:

1. The code begins by creating a `StringTokenizer` object named `tokeni


2. The `countTokens()` method is used to get the total number of tokens
3. An array called `stringArray` is created with the size equal to `tok
4. The `nextToken()` method is used in a loop to iterate through each t
5. Finally, a `for` loop is used to print each element in the `stringAr

**Output**:

```java
Hello
World
How
Are
You?

 
Applications of StringTokenizer Forum Donate

Support our charity


StringTokenizer can beand our mission.
useful Donate
in various to freeCodeCamp.org.
scenarios, including:

Parsing input data that is structured with a consistent


delimiter.

Extracting individual words or components from a sentence


or paragraph.

Splitting comma-separated values (CSV) into separate


elements.

Tokenizing text for lexical analysis or language processing


tasks.

Pros of using StringTokenizer :

Simplicity: The syntax of StringTokenizer is straightforward


and easy to understand, making it accessible for beginners.

Efficiency: StringTokenizer is efficient in terms of memory


and performance compared to regular expressions or manual
character-based splitting.

Flexible Delimiters: You can specify multiple delimiters or


use a predefined set of delimiters, allowing for versatile
tokenization.

Iterative Processing: StringTokenizer allows you to process


tokens iteratively, making it convenient for handling large
strings without loading everything into memory at once.

Cons of using StringTokenizer :

Limited Functionality: StringTokenizer lacks some advanced


features found in modern alternatives, such as regular
expressions, which offer more flexibility in tokenizing
Forum Donate
complex patterns.
Support our charity and our mission. Donate to freeCodeCamp.org.
No Support for Regular Expressions: Unlike other methods
like the split() method, StringTokenizer cannot use regular
expressions as delimiters, limiting its tokenization
capabilities.

No Support for Empty Tokens: StringTokenizer does not


handle empty tokens by default. If you have consecutive
delimiters, they are treated as a single delimiter, potentially
leading to unexpected results.

Legacy Class: StringTokenizer is part of the legacy Java


collections framework and does not implement the Iterable
interface, which means it cannot be used in enhanced for-
loops.

How to Convert Each Character


in a String to an Array Element
Manually
In certain situations, you may need more control over the
conversion process or want to customize it according to specific
requirements.

In such cases, you can convert a string to an array by manually


iterating over each character in the string and assigning them to
individual elements in the array.

Example code demonstrating manual conversion:

string = "Hello, World!"


array = []
for char in string:
Forum Donate
array.append(char)

Support our charity and our mission. Donate to freeCodeCamp.org.


print(array)

Explanation:

1. We define a string variable named string with the value


"Hello, World!".

2. We initialize an empty list called array .

3. We use a for loop to iterate over each character char in


the string .

4. Inside the loop, we use the append() method to add each


character char to the array .

5. After the loop completes, we print the array to see the


output.
Output:

['H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!']

Pros of manual conversion approach:

Provides full control over the conversion process.

Allows customization or manipulation of the characters


before assigning them to the array.

Works well when you need to perform additional operations


during the conversion.

Cons of manual conversion approach:


Requires more code and manual handling compared to built- Donate
Forum
in methods like toCharArray() or split() .
Support our charity and our mission. Donate to freeCodeCamp.org.
May be less efficient for large strings due to the manual
iteration process.

Increases the risk of errors if not implemented correctly.

Note: you should choose the manual conversion approach when you
specifically need to perform custom operations during the
conversion process. Otherwise, the built-in methods like
toCharArray() or split() are recommended for simplicity and
efficiency.

Comparison of the Different


Methods
1. toCharArray() :

2. Simple and straightforward method.

3. Returns a character array representing the string.

4. Suitable for general conversions without specific


requirements.

5. **split()** :

6. Splits the string into an array based on a specified delimiter.

7. Useful when you want to separate the string into substrings.

8. Provides flexibility in choosing the delimiter pattern.

9. StringTokenizer:

10. Specifically designed for tokenizing strings based on


delimiters.

11. Allows customization of delimiter characters.


12. Suitable when you need fine-grained control over Forum
the Donate
tokenization process.
Support our charity and our mission. Donate to freeCodeCamp.org.
13. Manual conversion:

14. Provides full control over the conversion process.

15. Allows customization and additional operations on


characters.

16. Recommended when specific requirements or manipulations


are needed during conversion.

Why Should You Know How to


Convert a String to an Array in
Java?
The importance of converting a string to an array in Java lies in the
versatility and flexibility it offers for manipulating and processing
data. Here are a few key reasons why being able to convert a string
to an array is important in Java:

Data Manipulation: Arrays provide a structured way to store


and manipulate data in Java. By converting a string to an
array, you can access individual characters or substrings,
modify the data, and perform various operations such as
sorting, searching, or filtering.

Algorithmic Operations: Many algorithms and data


structures in Java require input data in the form of arrays. By
converting a string to an array, you can easily apply these
algorithms and perform operations like sorting, reversing, or
extracting specific elements.

Text Parsing and Analysis: Strings often contain structured


or delimited data, such as CSV (Comma-Separated Values) or
JSON (JavaScript Object Notation). Converting a string to an
array allows you to split and parse the data, enabling further
Forum Donate
analysis, processing, or extraction of specific information.
Support our charity and our mission. Donate to freeCodeCamp.org.
String Manipulation: While strings have their own set of
methods for manipulation, arrays offer additional flexibility.
Converting a string to an array allows you to leverage array-
specific operations like indexing, slicing, or joining to
manipulate the data more efficiently or achieve specific
formatting requirements.

Interoperability: In certain scenarios, you may need to


convert a string to an array to interface with libraries or APIs
that expect array-based input. By performing the conversion,
you can seamlessly integrate your string data with external
components, ensuring compatibility and enabling seamless
data exchange.

Conclusion
In this article, we discussed various methods to convert a string to
an array in Java.

We started with an introduction to the importance of this


conversion between strings and arrays in Java.

Then, we explored four different approaches: using the


toCharArray() method, splitting the string using the split()
method, utilizing a StringTokenizer , and manually converting each
character to an array element. We covered each method in detail,
including their syntax, usage, example code, and pros and cons.

Let's connect on Twitter and on LinkedIn. You can also subscribe to


my YouTube channel.

Happy Coding!
Forum Donate

Support
If you our charity
read this and the
far, thank our author
mission.to
Donate
show to freeCodeCamp.org.
them you care.
Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has


helped more than 40,000 people get jobs as developers.
Get started
ADVERTISEMENT

freeCodeCamp is a donor-supported tax-exempt 501(c)(3) charity organization (United States


Federal Tax Identification Number: 82-0779546)

Our mission: to help people learn to code for free. We accomplish this by creating thousands of
videos, articles, and interactive coding lessons - all freely available to the public.

Donations to freeCodeCamp go toward our education initiatives, and help pay for servers,
services, and staff.

You can make a tax-deductible donation here .

Trending Books and Handbooks

Learn CSS Transform Build a Static Blog Build an AI Chatbot


What is Programming? Python Code Examples Open Source for Devs
HTTP Networking in JS Write React Unit Tests Learn Algorithms in JS
How to Write Clean Code Learn PHP Learn Java
Forum Donate
Learn Swift Learn Golang Learn Node.js
Support our charity and our mission. Donate to freeCodeCamp.org.
Learn CSS Grid Learn Solidity Learn Express.js
Learn JS Modules Learn Apache Kafka REST API Best Practices
Front-End JS Development Learn to Build REST APIs Intermediate TS and React
Command Line for Beginners Intro to Operating Systems Learn to Build GraphQL APIs
OSS Security Best Practices Distributed Systems Patterns Software Architecture
Patterns

Mobile App

Our Charity

About Alumni Network Open Source Shop Support Sponsors Academic Honesty

Code of Conduct Privacy Policy Terms of Service Copyright Policy

You might also like