Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String to char array and to string array

How can I can convert char array to string array?

For example "Text not text" → "Text not text" as char array → "Text" "not" "text"

I understand how to "Text not text" → "Text not text", but dont know how to

"Text not text" as char array → "Text" "not" "text"

Here is code example, but it does not work

public class main {
    public static void main(String[] args) {
        StringBuffer inString = new StringBuffer("text not text");
        int n = inString.toString().replaceAll("[^a-zA-ZА-Я а-я]", "")
                .split(" ").length;
        char[] chList = inString.toString().toCharArray();
        System.out.print("Text splited by chars - ");
        for (int i = 0; i < chList.length; i++) {
            System.out.print(chList[i] + " ");
        }
        System.out.println();
        String[] temp = new String[n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < chList.length; j++) {
                if (chList[j] != ' ') {
                    temp[i] = new String(chList);
                }
            }
            System.out.println(temp[i]);
        }
    }

}
like image 696
Anton Artemov Avatar asked Apr 21 '26 04:04

Anton Artemov


2 Answers

So you have a char array as following am I right:

char[] chars = new char[] {'T', 'e', 'x', 't', ' ', 'n', 'o', 't', ' ', 't', 'e', 'x', 't'};

Then what you want to get is separate words Text, not and text ??

if so, then do the following:

String newString = new String(chars);
String[] strArray = newString.split(" ");

now strArray is your array.

like image 122
anvarik Avatar answered Apr 23 '26 19:04

anvarik


Use the String.split() method.

like image 22
JB Nizet Avatar answered Apr 23 '26 17:04

JB Nizet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!