Poppy
Poppy

Reputation: 3092

How to add alternate elements to a String array

I have a String - "Hello@World@Good@Morning"

I want to add alternate words to a string array. Example, from the above string, i should add only Hello and good to my new array.

for (String s   : StringsTokens) {
            myStringArray = s.split(Pattern.quote("@"));

        }

How do i add only alternate elements to string array.

Upvotes: 2

Views: 588

Answers (2)

Rohit Khirid
Rohit Khirid

Reputation: 49

Looking at the patter you need to add words located at even positions.

So after splitting the string with the below code, to get a string array:

String[] words = string.split("@");

And initialising an ArrayList to use in your loops:

ArrayList<String> arList = new ArrayList<>();

you will run a for loop with :

for (int i=0 ; i<words.length ; i+=2) {
     // store the words in ArrayList like
     arList.add(words[i]);
}
//Convert ArrayList to Array and re-initialise ArrayList for the next String
String[] newArray = arList.toArray();
arList = new ArrayList<String>();

Upvotes: 3

Halayem Anis
Halayem Anis

Reputation: 7795

Try with this:

        List<String> result = new ArrayList<>();
        String[] src = "Hello@World@Good@Morning".split( "@" );
        for ( int i=0 ; i < src.length ; i++ ) {
            if( i%2 == 0 ) {
                result.add( src[i] );
            }
        }
        System.out.println(result);

output: [Hello, Good]

Upvotes: 0

Related Questions