1

I have strings in array I want to split them into char array? is it possible??

I did this:

    // skipped the portion of code
    void somefunction(String[] gf){
      char[] charArrays = new char[500];
      charArrays = gf.toCharArray();   // not allowing to use toCharArray

    // skipped the portion of code
    }
1
  • 1
    When I see such code: char[] charArrays = new char[500];charArrays = gf.toCharArray(); I know where the perfomance gain of new processors goes. Commented May 10, 2014 at 17:15

4 Answers 4

3

gf is a String[]. You can apply the method in a single String instead:

for (String s : gf) {
    charArrays = s.toCharArray();
}

Here's a more concrete example of what you want/need to achieve (IMO):

void somefunction(String[] gf) {
    List<char[]> data = new ArrayList<char[]>();
    int wholeSize = 0;
    for (String s : gf) {
        char[] charArray = s.toCharArray();
        data.add(charArray);
        wholeSize += charArray.length;
    }
    char[] wholeStringIntoCharArray = new char[wholeSize];
    int i = 0;
    for (char[] charArray : data) {
        for (char c : charArray) {
            wholeStringIntoCharArray [i++] = c;
        }
    }
    //return wholeStringIntoCharArray;
}
Sign up to request clarification or add additional context in comments.

8 Comments

where is function ending bro?
@user3508182 it would be better if you specify what's your real problem and how are you trying to solve it.
java.lang.NullPointerException
so far I am unable to split the string[] to char[]. bcz after conducting ths I have to make a cross_over task
stack or stacktrace? I know abt stack which follows first-in-lastout but I don't know stacktrace
|
2
    int size = 0;
    for (String s : input) {
        size += s.length();
    }

    char[] output = new char[size];
    int start = 0;
    for (String s : input) {
        System.arraycopy(s.toCharArray(), 0, output, start, s.length());
        start+=s.length();
    }

Comments

0

Here's a shorter version:

    String[] stringArray = new String[]{"abc", "qwe", "www"};
    List<Character> charList = new ArrayList<Character>();
    for (String string : stringArray) {
        for (char ch : string.toCharArray()) {
            charList.add(ch);
        }
    }
    Character[] finalArray = charList.toArray(new Character[0]);

Comments

0

You wrote this: I have strings in array I want to split them into char array? is it possible??

YES it is possible. You must join first and then split in an array of characters. try the following:

String result = ("" + Arrays.asList(gf)).replaceAll("(^.|.$)", "").replace(", ", "" );

char[] charArrays = result.toCharArray();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.