Reputation: 3092
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
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
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