πŸ” Java How-To Examples
Estimated reading: 3 minutes 40 views

πŸ”  Java: How to Convert a String to an Array (With Examples)


🧲 Introduction – Why Convert a String to an Array?

Converting a string into an array is a common task in Java programming. Whether you’re analyzing individual characters, splitting words, or processing CSV-like input β€” breaking down strings into arrays is essential for data parsing and transformation.

βœ… In this guide, you’ll learn:

  • How to convert a string to a character array
  • How to split a string into a word array
  • How to split by custom delimiters (comma, hyphen, etc.)
  • How to handle edge cases and best practices

πŸ”‘ Method 1: Convert String to Character Array

public class StringToCharArray {
    public static void main(String[] args) {
        String str = "Java";
        char[] chars = str.toCharArray();

        for (char c : chars) {
            System.out.print(c + " ");
        }
    }
}

βœ… Explanation:

  • toCharArray() converts a String into an array of characters.
  • Great for character-level operations, such as reverse, encryption, or counting.

🧾 Method 2: Convert String to String Array (Split by Space)

public class StringToWordArray {
    public static void main(String[] args) {
        String sentence = "Java is awesome";
        String[] words = sentence.split(" ");

        for (String word : words) {
            System.out.println(word);
        }
    }
}

βœ… Explanation:

  • split(" ") breaks the string into substrings (words) by space.
  • Suitable for word processing and natural language operations.

πŸ”§ Method 3: Split String by Comma or Other Delimiters

public class SplitByComma {
    public static void main(String[] args) {
        String data = "apple,banana,grape";
        String[] fruits = data.split(",");

        for (String fruit : fruits) {
            System.out.println(fruit);
        }
    }
}

βœ… Explanation:

  • Use split(",") for comma-separated strings (e.g., CSV).
  • You can also use other delimiters like "\\|", "-", ":", etc.

πŸ“˜ Common Delimiters:

DelimiterPattern
Comma","
Space" " or "\\s+"
Pipe`”\
Tab"\\t"

πŸ“˜ Method 4: Convert String of Digits to Integer Array

public class StringToIntArray {
    public static void main(String[] args) {
        String digits = "1 2 3 4 5";
        String[] parts = digits.split(" ");
        int[] numbers = new int[parts.length];

        for (int i = 0; i < parts.length; i++) {
            numbers[i] = Integer.parseInt(parts[i]);
        }

        for (int num : numbers) {
            System.out.print(num + " ");
        }
    }
}

βœ… Explanation:

  • Splits a space-separated string.
  • Parses each substring into an integer using Integer.parseInt().

⚠️ Warning: Make sure the input only contains numbers, or handle exceptions using try-catch.


🧼 Best Practices

  • βœ… Always trim() the string if unsure of leading/trailing spaces.
  • βœ… Use regex like "\\s+" to split on any whitespace.
  • ❗ Validate numeric conversions using try-catch blocks to avoid NumberFormatException.
  • βœ… Use toCharArray() only for per-character logic β€” not for token parsing.

πŸ“Œ Summary – Convert String to Array

Java provides powerful and flexible tools for breaking down strings into arrays β€” whether it’s characters, words, or numbers.

🧾 Key Takeaways:

  • Use .toCharArray() for character-level operations
  • Use .split() for word/token-based splitting
  • Convert split strings to int[] or double[] with parseInt() / parseDouble()
  • Choose the delimiter based on your use case (" ", ",", "\\|", etc.)

❓FAQs – Convert String to Array in Java

❓ How do I convert a string to a character array in Java?

Use toCharArray() method: char[] arr = str.toCharArray();.

❓ What is the difference between toCharArray() and split()?

  • toCharArray() splits a string into individual characters.
  • split() breaks a string by delimiters (spaces, commas, etc.).

❓ How do I convert a comma-separated string to an array?

Use split(","):

String[] arr = str.split(",");

❓ Can I convert a string of numbers to an int[]?

Yes. First split the string and then use Integer.parseInt() in a loop.

❓ How do I split a string by multiple spaces?

Use regex split("\\s+").


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Convert String to Array

Or Copy Link

CONTENTS
Scroll to Top