0
String newwords="hi pls solve this";

mStrings[]= {"abc","def","ghi"};
mStrings = mStrings+newwords.split(" "); //wrong

I know this code is wrong, but am expecting content in mStrings as {"abc","def","ghi","hi","pls","solve","this"}. Is there any operation to make this?

Thanks.

3
  • where in code you attempted to add element ? Commented Jun 7, 2014 at 4:07
  • am indicated that as wrong. in my code. sorry am a beginner. Commented Jun 7, 2014 at 4:08
  • use arraylist for further adding the data in array Commented Jun 7, 2014 at 6:32

3 Answers 3

2

Use StringTokenizer class to split the string into words/tokens and then add each of them to an ArrayList. You cannot increase/decrease the size of array and so you need to use ArrayList.

Sign up to request clarification or add additional context in comments.

Comments

1

You can't change the size of an array in Java, if you need to do this, either you need to allocate a new array, move over the old values, then add the new ones OR you need to use an ArrayList.

Comments

0

You can use Apache Commons Lang for this. I tried your problem and got the result as you asked for. Heres the code:

public class JavaTest {
public static void main(String[] args) {
    String newwords = "hi pls solve this";
    String mStrings[] = { "abc", "def", "ghi" };
    String[] msStrings = ArrayUtils.addAll(mStrings, newwords.split(" "));
    for (String s : msStrings) {
        System.out.println(s);
    }
}
}

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.