×

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

Set Value to Enum in Java

In this article, you will be acknowledged about Enum in java. Most importantly you will learn how to set value to Enum or how to practically customize a value to...

3 minutes read.

Java gc()

Garbage collection Java language provides different ways to perform the task of memory management. In Java, objects are declared and assigned references. Once lifeof an object is completed it is dereferenced...

4 minutes read.

Java Switch string

A multi-way branch statement is the switch statement. It offers a simple method for allocating execution to various code sections according to the expression's value. Primitive data types, including bytes,...

3 minutes read.

Rehashing in Java

The most crucial idea mostly in the data structure is hashing, which is utilized to change a particular key into some other value. The hash function can be used to...

7 minutes read.

Java Integer max() method

The max() method of Integer class returns the greater of two int values. It returns the same result as by calling Math.max. Syntax public static int max(int a, int b) Parameters The parameters ‘a’...

2 minutes read.

Java Location

PATH is an environmental variable that the system software now uses to find executable files (.exe) or Java binaries ( java or javac command). Once chosen, a route cannot be...

3 minutes read.

What is anagram in Java?

In this section will explain what an anagram is in Java and demonstrate how to determine whether or not a text is an anagram. In Java interviews, the anagram Java...

4 minutes read.

Conditional operator in Java

In Java, there are around eight operators, and among them, three operators are used to evaluate the condition and decide the Result based on the Result of the evaluated condition. Below...

4 minutes read.

Java Trim

Leading and leaving spaces are removed by the built-in Java String trim() method. Space seems to have the Unicode element of "x0040." Java trim() function looks for all of these...

3 minutes read.

Java Integer sum() method

The sum() method of Java Integer class add the two specified integers values. It returns the same result as given by + operator. Syntax public static int sum (int a, int b)  Parameters The...

1 minute read.

What is the ambiguity problem in Java?

The ambiguity problem in Java occurs when a method or constructor is overloaded with two or more methods with the same name but different parameters. This can confuse when multiple...

6 minutes read.

Java Arrays

An array is an object that stores a collection of values. An array can store two types of collection data: objects and primitives. An array is a collection of values which...

2 minutes read.

Menu Driven Program in Java

Menu Driven Program in Java The menu-driven program in Java is a program that displays a menu and then takes input from the user to choose an option from the displayed...

3 minutes read.

Stable Marriage Problem in Java

Given N men and N women, the Stable Marriage Problem asks you to match up the men and women in such a way that there are never any two people...

6 minutes read.

Java Math negateExact() Method

The negateExact() method of Math class returns the negation for the specified argument, throwing an exception if the result overflows an int or a long. Syntax: public static int negateExact (int a)public...

1 minute read.

Java Generate UUID

What java Generate UUID? A 128-bit long value that is universally unique serves as the basis for the terms UUID (Universally Unique Identifier) and GUID (Globally Unique Identifier). Hexadecimal (octet) digits...

5 minutes read.

Java Integer hashCode() method

The hashCode()  method of Java Integer class returns a hash code for this Integer.  Syntax public int hashCode() public static int hashCode(int value)  Parameters The parameter ‘value’ represents a value whose hash code...

1 minute read.

How to check valid date in Java?

Every time we get data for any application, we must first ensure that it is accurate before continuing with any further processing. We might have to confirm the following while dealing...

4 minutes read.

How to install Java in Windows 10

To make programs that can run on our systems, we need to install the programming language related software in our systems. Different programming language requires a different type of software aka...

6 minutes read.

Median Of Stream Of Running Integers in Java

An integer array is given to us. Compute the median of the elements traversed so far in the input array. For the sake of simplicity, assume that there are no...

10 minutes read.