×

How to convert String to String array in Java

A String in Java is a thing that indicates a collection of letters. We must include the String class from java.lang package if we want to be using strings. An array containing strings with such a set length is indeed the String array. For converting a String to a String array, there are 5 methods.

Example:

Input: String=“Om Ram”

Output:String[]=[Om,Ram]

Here are some of them:

  1. Using the String.split() function
  2. creating loops
  3. Employing the Set.toArray() method
  4. Applying the String tokenizer
  5. Using the Pattern.split() method

Method 1: Using the String.split() function

Approach:

  1. Create a string-typed array.
  2. String array for splitting an array.
  3. String name.split() can be used to divide the provided string . 
  4. Should print the divided string array.

StringArr.java

// This program is for converting the string to a String array
// by using the str.split() method
// import section
import java.io.*;
// Main section
public class StringArr {
 // Main method of the program
 public static void main(String[] args)
 {
  // Given input string to convert to string array
  String st = "Java Programming Language";


  String stArray[] = st.split(" ");


  System.out.println("Given String is: " + st);
  System.out.println("Converted String array : [ ");


  // Iterating over the string
  for (int i = 0; i < stArray.length; i++) {
   // The array of elements is printed
   System.out.print(stArray[i] + ", ");
  }


  System.out.print("]");
 }
}

Output:

How to convert String to String array in Java

Method 2: By using the loops

ArrayHash.java

//  This program is for converting the string to a String array
// by using the HashSet and the set classes
// import section
import java.io.*;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;


// Main section
public class ArrayHash{
 // 1st method
 // converting string to string[] array
 public static String[] method(Set<String> string)
 {
  // Create String[] of size of setOfString
  String[] stringarray = new String[string.size()];


  //elements are copied to set array
  //by using the for loop
  int position = 0;
  for (String st: string) {
   stringarray[position++] = st;
  }


  // returning the formed character array
  return stringarray;
 }


 // 2nd Method
 // Main method
 public static void main(String[] args)
 {
  // user input
  String st= "Java Programming language";


  // object set_String is created
  Set<String> set_string
   = new HashSet<>(Arrays.asList(st));


  // Printing the setOfString
  System.out.println("The given String is: " + st);


  // the set is converted to a string array
  String[] Stringarray = method(set_string);


  // printing the array consisting of strings
  // by using the arrays.toString() method
  System.out.println("The String array is: "
      + Arrays.toString(Stringarray));
 }
}

Output:

How to convert String to String array in Java

3. Using the Set.toArray() method

Approach:

  1. Transform the provided string into a group of strings.
  2. Make a blank string array now.
  3. By giving a blank array of the integer type to set.toArray(), you may transform the string set to an array of strings.
  4. Display the string array.

Example: Stringarr.java

//This program is for converting the string to string array
//By using the method Set.toArray() 
//import section
import java.io.*;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
// Main section
public class Stringarr {
 // 1 st Method
 // to convert the string to string array
 public static String[] convert(Set<String> setOfString)
 {
  // a string String[] is created
  String[] arrayString  = setOfString.toArray(new String[0]);
  // returning the resultant string
  return arrayString;
 }
 // 2 Method
 //Main Method
 public static void main(String[] args)
 {
  //creating the string 
  String st = "Java Programming language";
  //Set of string
  Set<String> strings
   = new HashSet<>(Arrays.asList(st));
  //printing the string
  System.out.println("Given String: " + st);


  // Converting Set to String array
  String[] stringarray = convert(strings);
  // Print the arrayOfString In the print statement
  // the method is used (Arrys.toString())
  System.out.println("The converted String array : "
      + Arrays.toString(stringarray));
 }
}

Output:

How to convert String to String array in Java

4. Using a string tokenizer

A string tokenizer is a tool that breaks up a string object into progressively smaller pieces. Tokens refer to these more compact components.

  1. Tokenize the supplied string.
  2. Make a type string array with the token counts' sizes in it.
  3. Should save these tokens in a string array.
  4. Displaying the string array in the print statement.

Example: StringToken.java

// This program is for converting the string to a String array
// by using the string tokenizer class
// importing the required packages
import java.io.*;
import java.util.StringTokenizer;
// Main section of the program
public class StringToken {
 // Main method of the class 
 public static void main(String[] args)
 {
  // the integer value iss declared
  // to 0
  int i = 0;
  // giving the user input
  String st = "Java Programming Language";
  // the string is divided into tokens
  // using the delimiter
  StringTokenizer strtokenizer
   = new StringTokenizer(st);
  String[] stringarray
   = new String[strtokenizer.countTokens()];
  // the tokens are appended to the array
  while (strtokenizer.hasMoreTokens()) {
   stringarray[i] = strtokenizer.nextToken();
   i++;
  }
  //printing the given string
  System.out.print("The given String :" + st);
  // displaying the string array
  System.out.print("\nThe String array is  : [ ");
  // the string array is printed
  // by using the loos
  for (String s: stringarray) {
   System.out.print(s + " ");
  }
  System.out.print("]");
 }
}

Output:

How to convert String to String array in Java

5. Method of using the pattern.split() function.

Using the split() function, a provided text is divided into an array by a predefined pattern. By providing a certain pattern, we may divide our string. 

Approach:

  1. Create a pattern (REGEX)
  2. Then use the compilation technique to make a pattern.
  3. Then divide the string utilizing the pattern.
  4. Use split() using a particular pattern and save the results in the array.
  5. Print the array of strings

PatternSplit.java

// This program is for converting the string to a String array
// by using the pattern.split() method
// importing the required packages
import java.io.*;
import java.util.regex.Pattern;
// Main section
public class PatternSplit {
// Main method of the program
public static void main(String[] args)
{
// user input as the string
String s = "Java Programming Language";


// Step:1 defining the re expression
String mypattern = "\\s";


// Step2:The pattern is created by using the compile method
Pattern patt = Pattern.compile(mypattern);


// Step 3:The arry is created by using the declared pattern in above
String[] stringarray = patt.split(s);


// Printing the given string
// and also it's converted array
System.out.print("The given String is : " + s);
System.out.print("\nThe String array is : [ ");


// The String iterated using the for loop
for (int i = 0; i < stringarray.length; i++) {
// the Stringarray is printed
System.out.print(stringarray[i] + " ");
}


System.out.print("]");
}
}

Output:

How to convert String to String array in Java

Related Topics

Thread Program in Java

Thread Program in Java Thread program in Java is the continuation of multithreading program in Java. In this topic, we will learn about the usage of threads, race condition in multithreading,...

8 minutes read.

Java Boolean compareTo() method

The compareTo() method of Java Boolean class compares the Boolean argument with the Boolean instance and returns integer value, zero, or negative 1, or positive 1 based on the result...

2 minutes read.

Java Math multiplyFull() Method

The multiplyFull() method of Math class returns the exact product of the arguments. Syntax: public static long multiplyFull (int x, int y) Parameters: The parameters ‘x’ and ‘y’ represent the first value and second...

1 minute read.

Pangram Program in Java

If a string comprises all alphabet letters from A to Z or from a to z without regard to case, it is referred to as a pangram. Some examples of pangram...

3 minutes read.

Java Map Example

In Java, the Map is an interface that is used mainly to denote key and value pairs. The central concept and theme of this mapping in the java collection framework...

4 minutes read.

Java ArrayList

Java ArrayList Class A Java ArrayList class is a dynamic array which is used to store the elements. It is a part of collection framework. It implements the List Interface and inherits the...

12 minutes read.

How to Create Singleton Class in Java

In this tutorial, we will discuss the singleton class and how to create it. Introduction Java is a purely object-oriented programming language. It consists of classes and objects. But Singleton is one...

4 minutes read.

Union in Java

Sets.union() method in Java returns an immutable representation of both the union of two sets. Every element that is present in either backup set is included in the set that...

2 minutes read.

Java List Interface

List interface is used when we have to order a collection which contains duplicate entries. Like an array, the elements of its implementation classes are retrieved and inserted at a...

2 minutes read.

Model Class in Java

In this section, we will be acknowledged about the model class in Java, its purpose and its uses. Also, we will learn how is this created and leveraged in java. Model...

4 minutes read.

Java Logo

Java is a prominent and extensively used object-oriented programming language. In 1995, Sun Microsystems created it. Later in 2009, Oracle Corp takeover Java. History of Java Logo The name of the island...

3 minutes read.

String to JSON in Java

Nowadays, receiving data in JSON String format rather than XML is quite frequent. Java does not transform JSON String to JSON Object when dealing with JSON String. However, using the...

3 minutes read.

How to Split String by Comma in Java

strsplit() technique permits you to break a string given the explicit Java string delimiter. The Java string split property is frequently a space or a comma(,) that you want to...

7 minutes read.

Java String charAt() method

It returns the char value present in the string at the specified index. Here, index value can not be greater than length() -1. Syntax: public char charAt (int index) Parmeters It accepts only...

3 minutes read.

Java Future Example

Future is an interface in the Java language that is a part of  java.util.concurrent package. It serves as a symbol for the output of an asynchronous computation. The interface offers ways to determine whether a computation has finished,  wait for it to finish, and receive its result. Once the task or calculation is finished, it cannot be undone. A Future interface offers ways to determine whether the computation is finished, to wait for it to finish, and to receive the computation's results. When the computation...

3 minutes read.

How to add 6 Months to the Current Date in Java?

In this tutorial, we will learn how to add 6 months to the local or current date in Java language. We will begin our topic with basic concepts and would...

3 minutes read.

Character Array in Java

A character array is an array which holds values of character data types. It is different from a string array. The character array, string, and StringBuffer classes in the Java...

4 minutes read.

How to take String Input in Java

There are various ways to take String input in Java. In this section, we are going to discuss how to take String input in Java. There are following ways to...

5 minutes read.

Difference between next() and nextline() in Java

One of the simplest methods for receiving input of the basic data types, also including int, double, and strings, in Java, is to use the Scanner class, which is part...

3 minutes read.

Alien language problem in Java

Given the alphabetic sequence of an alien language, given a sorted dictionary (array of words) for the languages. Example: Words = { "aac", "abc", "aaa" } Output c, a, b Algorithm: (1) Compare two words that...

3 minutes read.