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.
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>();
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]
Related
public static String[] removeCharacters(String[] arr){
String[] str = new String[arr.length];
for (int i = 0; i <arr.length; i++) {
if(Character.isLetter(arr[i].charAt(i)))
str[i] += arr[i].charAt(i);
else
str[i] = "";
}
return str;
}
I'm trying to write a method that returns to String array and takes an String array argument.
I need remove special characters from the element and return the element without specials.
For example;
["Hel123&$$o", "#$%World", "###"]
will return to
["Hello", "World", "",] as a output.
I also converted back to String, remove those special characters and split back again to an Array but when i convert to String it all comes together and there is no split point and I don't want to do it with Regex so i'm trying to do without it. With my solution I'm getting null so i couldn't fix.
Here's a changed version. You have to use a nested for loop - the first iterates over the input String[] and the nested one over the char[] in each string.
I have also used some variables in place of repeated array references for easy reading.
public class StrArray{
public static void main( String[] args ){
String[] input = new String[]{ "Hel123&$$o", "#$%World", "###" };
String[] strArr = removeCharacters( input );
Arrays.stream( strArr ).forEach( s -> System.out.println( "'" + s + "'" ) );
}
public static String[] removeCharacters( String[] arr ){
String[] str = new String[ arr.length ];
for( int i = 0; i < arr.length; i++ ){
String input = arr[ i ];
/* If the input string in empty, skip.*/
int k = 0;
if( input == null || input.length() == 0 )
str[ i ] = "";
else{
/* Construct a char[] containing all the relevant chars. */
char[] chars = new char[ input.length() ];
for( int j = 0; j < input.length(); j++ ){
char c = input.charAt( j );
if( Character.isLetter( c ) ) chars[ k++ ] = c;
}
/* Now, convert the char[] into a string. */
str[ i ] = String.valueOf( chars, 0, k );
}
}
return str;
}
}
I have quoted each string while printing. Hence, running this gives the following output.
'Helo'
'World'
''
The problem is that you are iterating over the array of strings but not over the array of characters of each string. You can use a loop to iterate over the array of Strings and a nested loop to iterate over the characters of each String.
Here I'm using StringBuilder to concatenate the Strings since it is more efficient than using +. This is because the String object is immutable, so each call for concatenation will create a new String object. On the other hand, StringBuilder is a mutable array of characters.
import java.util.Arrays;
public class MyClass {
public static void main(String args[]) {
String[] stringArray =
new String[]{ "Hell123&$$o", "#$%World", "###" };
System.out.println(
Arrays.toString(removeCharacters(stringArray)));
}
public static String[] removeCharacters(String[] arr) {
String[] str = new String[arr.length];
for (int i = 0; i < arr.length; i++) {
StringBuilder strBuilder = new StringBuilder();
for (int j = 0; j < arr[i].length(); j++) {
if (Character.isLetter(arr[i].charAt(j)))
strBuilder.append(arr[i].charAt(j));
}
str[i] = strBuilder.toString();
}
return str;
}
}
I am trying to double each letter in a list of Strings in an array loop.
For example:
["abc","def"] --> ["aabbcc","ddeeff"]
ArrayList<String> aa;
aa = new ArrayList<String>();
String res = "";
for(int i=0;i<words.size();i++){
char at = aa.get(i);
res=res+at+at;
}
return res;
I am still new to coding and as you can see, my code is a mess. Help is appreciated. Thanks in advance
You some problems with your implementation:
You interact over words array but uses the index over the aa. As it was never added items to it, you will get an ArrayIndexOutOfBoundsException.
You issue a return res but this will return only one string, not an array of words.
According to your example this can be done this way:
public static ArrayList<String> doubleWords(ArrayList<String> input) {
ArrayList<String> result = new ArrayList<>();
for (String string : input) {
String word = "";
for (int i = 0; i < string.length(); i++) {
word += ""+string.charAt(i)+string.charAt(i);
}
result.add(word);
}
return result;
}
Your output for an ArrayList with [abc, def] will be [aabbcc, ddeeff].
You need to iterate through your list of words and then for each word in the list iterate through the characters in the string, like so:
public ArrayList<String> doubleWords(ArrayList<String> words) {
ArrayList<String> doubledWords = new ArrayList<String>();
for (String word : words) {
String newWord = "";
for (int i=0; i<word.length(); i++) {
newWord = newWord + word.substring(i, i+1) + word.substring(i, i+1);
}
doubledWords.add(newWord);
}
return doubledWords;
}
Since Java 8 this can also be achieved in the following way:
String input = "abc";
StringBuilder builder = new StringBuilder();
input.chars().forEach(value -> builder.append((char)value).append((char)value));
Remeber to convert the int value back to a char before you append it.
Output for above program:
System.out.println(builder.toString());
// aabbcc
//response list
ArrayList<String> aa;
aa = new ArrayList<String>();
StringBuilder sb = new StringBuilder() ;
String word;
// iterate list of words
for(int i=0; i < words.size(); i++){
//get word
word = words.get(i);
//iterate each character in word
for(int j =0; j < words; j++) {
//append each char twice in StringBuilder
sb.append(word[j).append(word[j]);
}
//add word to output list
aa.add(sb.toString());
//empty StringBuilder for next word
sb.setLength(0);
}
return aa;
It can be done only by java stream api without any temporary variables:
List<String> result = listOfWords.stream().
map(value -> String.valueOf( // new result String(doubled word)
value.chars() // get chars for each original string
.mapToObj(i-> (char)i) // cast each char from int to char type
.map(c -> String.valueOf(new char[]{c, c})) // create doubled char string
.collect(Collectors.joining()))) // concatenate all doubled chars
.collect(Collectors.toList()); // collect result to list
For instance, if I have the string "Bob Bakes Brownies", is there any way I can get this method to produce a list of three strings: "Bob", "Bob Bakes", and "Bob Bakes Brownies"
Any feed back would be appreciated.
Create a list to return. Loop through the String looking for spaces. For each space that you find, add a substring to the list, that starts at the zero index and goes up to the space (not including the space).
When there are no more spaces, add the entire string to the list, and return.
You can use .split() to get an array of the individual words or use StringTokenizer
Good approach will be split(" ") the string, this will produce an array. Then you can iterate on the array when every time you concatenate the current array cell with StringBuilder or a normal concatenation and print the result on every iteration.
public void listOfStrings(String s){
ArrayList<String> result = new ArrayList<String>();
int p = 0;
for (int i = 0; i < s.length() ; i++) {
if(s.charAt(i) == ' ') {
result.add(p, s.substring(0, i));
p++;
}
if(i == s.length()-1)
result.add(p,s);
}
}
Try this:
static List<String> createStringList(String string) {
String[] parts = string.split(" ");
List<String> result = new ArrayList<>();
StringBuilder currentString = new StringBuilder();
for (int i = 0; i < parts.length; i++) {
if (i > 0) {
currentString.append(" ");
}
currentString.append(parts[i]);
result.add(currentString.toString());
}
return result;
}
public ArrayList<String> solution(String s){
ArrayList<String> result = new ArrayList<String>();
StringBuffer sb = new StringBuffer();
String[] array = s.split(" ");
for(String str:array){
sb.append(str);
result.add(sb.toString());
}
return result;
}
String string = "Bob Bakes Brownies";
List<String> list = Arrays.asList(string.split(" "));
my first question.
lets say i have arraylist of strings in java
ArrayList<string> s= new ArrayList<string>;
and it contains sorted list by size.
s.add("ab");
s.add("abc");
s.add("aab");
s.add("baab");
s.add("abcd");
what i want to do is, iterate the list and pick group of elements which has same length and put into seprate array of arrays.
Group 1 ab
Group 2 abc,aab and so on...
i am doing this in java please help
Since they're sorted by size already it's easy. Here's one way that works:
ArrayList<ArrayList<String>> listofLists = new ArrayList<ArrayList<String>>();
int length = -1;
for(String str : s) { // where s is your sorted ArrayList of Strings
if(str.length() > length) {
listofLists.add(new ArrayList<String>());
length = str.length();
}
listofLists.get(listofLists.size()-1).add(str);
}
At the end, listofLists will be an ArrayList of ArrayLists containing groups of Strings of the same length. Again, this depends on s (your ArrayList<String>) being sorted by size. Also, String must be capitalized there.
You can use this code "it works as you need"
import java.util.ArrayList;
public class Test{
public static void main(String[] args){
ArrayList<String> s = new ArrayList<String>();
s.add("ab");
s.add("abc");
s.add("aab");
s.add("baab");
s.add("abcd");
String[] group1 = new String[s.size()];
String[] group2 = new String[s.size()];
String[] group3 = new String[s.size()];
for(int i = 0 ; i < s.size() ; i++){
if(s.get(i).length() == 2)
group1[i] = s.get(i);
else if(s.get(i).length() == 3)
group2[i] = s.get(i);
else
group3[i] = s.get(i);
}
for(String ss : group1){
if(ss == null)
break;
System.out.println(ss);
}
System.out.println();
for(String ss : group2){
if(ss == null)
continue;
System.out.println(ss);
}
System.out.println();
for(String ss : group3){
if(ss == null)
continue;
System.out.println(ss);
}
}
}
I hope it useful for you.
Is this correct method to sort ArrayList?
The problem is that the list is not sorted.
out = new StringTokenizer(input.toString());
n = (out.countTokens());
for (int i = 0; i < n; i++) {
String[] words = { out.nextToken().toString() };
final List<String> wordList = Arrays.asList(words);
Collections.sort(wordList);
System.out.println(wordList.toString());
}
Each of your words[] arrays is composed of a single string, obtained from the next token of your StringTokenizer. And you are iterating in exact order of the tokenization. So yes, your output will not be sorted. I presume you wanted to do something like this:
out = new StringTokenizer(input.toString());
int count = out.countTokens():
List<String> wordList = new ArrayList<String>(count);
for(int i = 0; i < count; i++) {
wordList.add(out.nextToken());
}
Collections.sort(wordList);
But, don't use the tokenizer class, its legacy. The following code will serve you better:
List<String> wordList = Arrays.asList(input.split("\\s"));
Collections.sort(wordList);
out.nextToken().toString() give you one string. Your array length should be 1, I presume.
Even if you put this into a loop, you sort at each loop, you have to sort outside the loop.
StringTokenizer out = new StringTokenizer( input.toString());
List<String> wordList = new ArrayList< String >();
while( out.hasMoreTokens()) {
wordList.add( out.nextToken());
}
Collections.sort( wordList );
System.out.println(wordList.toString());