Str to array java

How to Convert String to Array in Java

Sometimes, we need to convert a string to array in Java based on some criteria to address one problem or another.

Unfortunately, Java does not provide any direct way to accomplish this automatically!

So, in this tutorial, we’ll try to cover in-depth the most commonly used methods to turn a string object into an array.

Feel free to check our article on how to convert an array to a string if you are curious about how to do the opposite.

Split String into an Array in Java

There are many options out there that you can use to tackle Java string-to-array conversion. We’ll walk you through from beginning to end so you can implement each method without getting confused.

Using split() Method

The split() method belongs to the String class and it’s mainly used to split a simple string into tokens.

This method returns a String[] array by splitting the specified string using a delimiter of your choice. The separator can be a string or a regular expression.

Let’s discover together how we can use the split() method to convert a string to an array:

 public class StringToArray < public StringToArray() < >public static void main(String[] args) < // TODO Auto-generated method stub String str = "Hello;dev;with;us"; // Split our String using ; separator String[] strarray = str.split(";"); if(strarray.length > 0)< for(String elm: strarray)< System.out.print(elm+" "); > > else< System.out.println("No elements to display!"); > System.out.println(""); // Split string using regular expression String str2 = "Hi buddy! Smile, sunshine is good for your teeth"; String[] strarray2 = str2.split("\\s"); if(strarray2.length > 0)< for(String elm: strarray2)< System.out.print(elm+" "); > > else< System.out.println("No elements to display!"); > > > // Example's output Hello dev with us Smile, sunshine is good for your teeth 

Using Pattern.split()

The main purpose of this split() method is to break the passed string into an array according to a given pattern defined using the compile method.

The following example will show you how to use the split() and the compile() methods to convert a String object to a String[] array using a regular expression:

 import java.util.regex.Pattern; public class StringToArrayPattern < public StringToArrayPattern() < >public static void main(String[] args) < // TODO Auto-generated method stub String mystr = "Azhwani From Tamassint"; // Define our REGEX String PATTERN = "\\s"; // Create a pattern using compile method Pattern pattern = Pattern.compile(PATTERN); // Create an array of strings using the pattern we already defined String[] strtoarray = pattern.split(mystr); // Print our array for (int i = 0; i < strtoarray.length; i++) < System.out.println("strtoarray[" + i + "] code comment">// Output strtoarray[0]=Azhwani strtoarray[1]=From strtoarray[2]=Tamassint 

Using StringUtils.split() Method

StringUtils is an utility class provided by the Apache Commons project. This class offers multiple null-safe methods related to String manipulation.

Читайте также:  Java itext convert html to pdf

It’s a good alternative since the java.lang.String package can’t handle all the String related operations.

In order to use StringUtils class, you need to import the commons-lang3 JAR file into your project. You can download it and import it manually or you can just use a dependency management tool like Maven or Gradle.

You can download the latest version of Apache Commons Lang 3 from here

The following is an example of how to use StringUtils to convert a particular string to an array in Java:

 import org.apache.commons.lang3.StringUtils; public class StringToArrayStringUtils < public StringToArrayStringUtils() < >public static void main(String[] args) < // TODO Auto-generated method stub String mystr = "Just#Trying#To#Test#StringUtils#Split#Method"; String [] splitedarray = StringUtils.split(mystr, "#"); for(int i=0; i< splitedarray.length; i++ ) < System.out.println( i + ") "+ splitedarray[i]); > > > 

Use stringUtils to split string to array

Using StringTokenizer Class

StringTokenizer is a legacy class that belongs to java.util package. It helps split a string object into small parts called tokens.

The process of breaking a string into multiple tokens is called String tokenization. Space is the default delimiter used for String tokenization!

Let’s see a simple example of how to use the StringTokenizer class to tokenize a string object in Java.

 import java.util.StringTokenizer; public class StringToArrayStringUtils < public StringToArrayStringUtils() < >public static void main(String[] args) < String str = "Just, trying to understand, StringTokenizer class, with an example"; // Tokenize a given string using the default delimiter StringTokenizer tokenizer1 = new StringTokenizer(str); String [] strarray1 = new String[tokenizer1.countTokens()]; // Add tokens to our array int i = 0; while(tokenizer1.hasMoreTokens()) < strarray1[i] = tokenizer1.nextToken(); i++; >for(String stritem : strarray1)< System.out.println(stritem); > System.out.println("----------------------------"); // Break a given string into tokens using , delimiter StringTokenizer tokenizer2 = new StringTokenizer( str,","); String [] strarray2 = new String[tokenizer2.countTokens()]; i = 0; while(tokenizer2.hasMoreTokens()) < strarray2[i] = tokenizer2.nextToken(); i++; >for(String stritem : strarray2)< System.out.println(stritem); > > > // Output Just, trying to understand, StringTokenizer class, with an example ---------------------------- Just trying to understand StringTokenizer class with an example 

Using Guava Library

Guava is a Java-based library developed by Google. It provides some great mechanisms and utilities for joining and splitting strings.

Читайте также:  Telegram bot python send photos

To use Guava library, you need to add it to your Java project first. If you are using Maven, you can include the Guava dependency into your POM file.

If you’re not a big fan of dependencies management tools, then you have to follow these steps:

  • Download the Google Guava JAR file.
  • Import the JAR file into your project.
  • Add the JAR file as a library.

The Guava’s Splitter class provides an interesting method called splitToList(). The Splitter uses a delimiter to split the given String into a collection of elements.

The separator can be specified as a single character, a fixed string, or a regex pattern!

Unlike other classes, Splitter provides a more object-orientated way to parse the string and split it.

The following example shows how to split a string object into a List:

 import com.google.common.base.Splitter; import java.util.List; public class StringToArrayGuava < public StringToArrayGuava() < >public static void main(String[] args) < String mystr = "Guava# is # # From Google! You can use it# to split Strings in Java"; // Create a splitter object, which you then use to do the splitting! // trimResults() : Trim the result // omitEmptyStrings() : Ignore empty elements Splitter mySplitter = Splitter.on('#') .trimResults() .omitEmptyStrings(); // Split string to List ListString> strList = mySplitter.splitToList(mystr); // Convert List to Array String[] myarray = strList.toArray(new String[strList.size()]); for (String item : myarray) < System.out.println(item); > > > // Output Guava is From Google! You can use it to split Strings in Java 

How to Convert String to char Array Java?

Java provides several ways to convert a string into an array of characters. So, let’s get an up-close look at some of the available methods.

Читайте также:  Java читать файл до символа

Using toCharArray() Method

This method of the String class returns an array of characters from a given string. The returned array has the same length as the length of the string.

The following example demonstrated how to convert a string object to char array using the toCharArray() method.

 public class StringToCharArray < public StringToCharArray() < >public static void main(String[] args) < // convert String to character array String str = "toCharArray"; char chararray[] = str.toCharArray(); for(char ch:chararray)< System.out.println(ch); > > > 

How to convert string to char array

Using getChars()

public void getChars(int start, int end, char[] arr, int arrstart) is used to copy characters from a given string into a char[] array.

  • start: Index of the first character of the string to copy.
  • end: Index after the last character to copy.
  • arr: Destination array where chars will be copied.
  • arrstart: The first index in array where the first character will be pushed.
 public class GetCharsExample < public GetCharsExample() < >public static void main(String[] args) < String mystr = "Testing getChars method"; char[] chararr = new char[8]; // copying string to char array mystr.getChars(8, 16, chararr, 0); for(char ch: chararr)< System.out.print(ch+" "); > > > // Output g e t C h a r s 

Java 8 chars() Method

chars() is a new method introduced in Java 8. It can be used to create an instance of Stream from a String object.

You can use the mapToObj() and the toArray() methods with chars() method to convert a string to array of characters.

 public class Java8Chars < public Java8Chars() < >public static void main(String[] args) < String mystr = "Java 8 Chars"; // Create character array from string Character[] arraychars = mystr.chars() .mapToObj(c -> (char) c) .toArray(Character[]::new); for(Character ch: arraychars)< if(Character.isLowerCase(ch)) System.out.print(ch+" "); > System.out.println(""); "hi java 8 chars".chars().forEach(c -> System.out.print((char)c+" ")); > > // Output a v a h a r s h i j a v a 8 c h a r s 

Conclusion

In this article, you learned how to convert string to array in Java. You learned also different ways of splitting a simple string into a char array.

Thanks for reading. Have a nice day!

Liked the Article? Share it on Social media!

Источник

Оцените статью