user3717039
user3717039

Reputation: 1

How to add new entries to string array in android/java?

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.

Upvotes: 0

Views: 71

Answers (3)

Illegal Argument
Illegal Argument

Reputation: 10358

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);
    }
}
}

Upvotes: 0

Florescent Ticker
Florescent Ticker

Reputation: 645

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.

Upvotes: 2

Gabe Sechan
Gabe Sechan

Reputation: 93728

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.

Upvotes: 1

Related Questions