Split String Array in Java (Android) - java

Let's say I have a String[] that looks like this:
private String[] motherOfStrings = {
"stringA",
"stringB",
"stringC",
"stringD",
"stringE",
}
Can I split it into multiple String[] like these?
private String[] childOfString1 = {
"stringA",
"stringB",
"stringC",
}
private String[] childOfString2 = {
"stringD",
"stringE",
}
Thanks guys :)
p.s., i did some search but most of the guides (if not all) are about splitting String[] into Strings, not another String[]. Is this even possible?

You can use split() method for every string in your array.
String stringByWhichYouWantToSplit = "C";
String[][] splittedStrings = new String[motherOfStrings][];
for(int i = 0; i < motherOfStrings.length; i++)
splittedStrings[i] = motherOfStrings.split(stringByWhichYouWantToSplit);
...if you want to split your strings by "C" ...
EDIT:
Now, when you edited question I see what you want. You have to create two arrays and copy into them strings from motherOfStrings. You can use System.arraycopy method.

Loop through array and split each String into String[] or better maintain a List<String>

Related

Converting array list to a string array

I've been trying to convert my string array list to a string array so I can print it but have been unable to do so.
This is the class I have, randomQuestion which takes in an array list from the gameQuestions method in the same class.
I have never tried to convert an array list using a loop before hence the difficulty, I was able to convert it fine with the code
String[] questions = data1.toArray(new String[]{});
But I need it to loop through using a for loop to store it in an array which I can then print one at a time once a question is answered successfully.
The error I'm receiving from netbeans is cannot find symbol
Symbol:methodtoArray(String[]) for the .toArray portion below.
public String[] randomQuestion(ArrayList data1) {
Collections.shuffle(data1);
for (int question = 0; question < 10; question++) {
ranquestions = data1.get(question).toArray(new String[10]);
}
return ranquestions;
}
Any help would be greatly appreciated.
You can use List.toArray(). Class List has a method:
<T> T[] toArray(T[] a);
Assuming you have an ArrayList<String>, you can use String.join(delimiter, wordList) in order to concatenate all the elements to a single String:
public static void main(String[] args) {
// example list
List<String> words = new ArrayList<String>();
words.add("You");
words.add("can");
words.add("concatenate");
words.add("these");
words.add("Strings");
words.add("in");
words.add("one");
words.add("line");
// concatenate the elements delimited by a whitespace
String sentence = String.join(" ", words);
// print the result
System.out.println(sentence);
}
The result of this example is
You can concatenate these Strings in one line
So using your list, String.join(" ", data1) would create a String with the elements of data1 delimited by a whitespace.
The question is how to create an array with only 10 elements of the list, if I understood correctly.
Streams (Java 8):
String[] ranquestions = data1.stream()
.limit(10)
.toArray(String[]::new);
Loop (based on question, avoiding unnecessary changes):
String[] ranquestions = new String[10];
for(int question = 0; question < 10; question++) {
ranquestions[question] = data1.get(question);
}
always assuming List<String> data1, if not some conversion is needed.
Example:
String[] ranquestions = data1.stream()
.limit(10)
.map(String::valueOf)
.toArray(String[]::new);
or, loop case:
ranquestions[question] = String.valueOf(data1.get(question));
You can do:
private String[] randomQuestions(ArrayList data){
Collections.shuffle(data);
return (String[]) data.toArray();
}
If you are sure you are getting a list of string (question) you can instead
private String[] randomQuestions(List<String> data){
Collections.shuffle(data);
return (String[]) data.toArray();
}
Edit 1
private static String[] randomQuestions(ArrayList data){
Collections.shuffle(data);
String[] randomQuestions = new String[data.size()];
for(int i=0; i<data.size(); i++){
randomQuestions[i] = String.valueOf(data.get(i));
}
return randomQuestions;
}

Remove elements from ArrayList after finding element with specific char

I have an ArrayList that contains a number of Strings, I want to be able to iterate through the ArrayLists contents searching for a string containing a semicolon. When the semicolon is found I then want to delete all of the Strings including and after the semicolon string.
So;
this, is, an, arra;ylist, string
Would become:
this, is, an
I feel like this is a very simple thing to do but for some reason (probably tiredness) I can't figure out how to do it.
Here's my code so far
public String[] removeComments(String[] lineComponents)
{
ArrayList<String> list = new ArrayList<String>(Arrays.asList(lineComponents));
int index = 0;
int listLength = list.size();
for(String str : list)
{
if(str.contains(";"))
{
}
index++;
}
return lineComponents;
}
This becomes trivial with Java 9:
public String[] removeComments(String[] lineComponents) {
return Arrays.stream(lineComponents)
.takeWhile(s -> !s.contains(";"))
.toArray(String[]::new);
}
We simply form a Stream<String> from your String[] lineComponents and take elements until we find a semicolon. It automatically excludes the element with the semicolon and everything after it. Finally, we collect it to a String[].
First of all I think you are confusing arrays and arraylists. String[] is an array of strings while ArrayList<String> is an arraylist of strings. Take into account that those are not the same and you should read Array and ArrayList documentation if needed.
Then, to solve your problem following the ArrayList approach you can go as follows. Probably it's not the optimum way to do it but it will work.
public List<String> removeComments(List<String> lineComponents, CharSequence finding)
{
ArrayList<String> aux = new ArrayList<String>();
for(String str : lineComponents)
{
if(str.contains(finding))
break;
else
aux.add(str);
}
return aux;
}
This example is just for performance and bringing back my old favorite arraycopy:
public String[] removeComments(String[] lineComponents) {
int index = -1;
for (int i = 0; i < lineComponents.length; i++) {
if ( lineComponents[i].contains(";") ) {
index = i;
break;
}
}
if (index == -1) return lineComponents;
return Arrays.copyOf(lineComponents, index);
}

Two dimensional string array in java

I am new to java please help me with this issue.
I have a string lets say
adc|def|efg||hij|lmn|opq
now i split this string and store it in an array using
String output[] = stringname.split("||");
now i again need to split that based on '|'
and i need something like
arr[1][]=adc,arr[2][]=def and so on so that i can access each and every element.
something like a 2 dimensional string array.
I heard this could be done using Arraylist, but i am not able to figure it out.
Please help.
Here is your solution except names[0][0]="adc", names[0][1]="def" and so on:
String str = "adc|def|efg||hij|lmn|opq";
String[] obj = str.split("\\|\\|");
int i=0;
String[][] names = new String[obj.length][];
for(String temp:obj){
names[i++]=temp.split("\\|");
}
List<String[]> yourList = Arrays.asList(names);// yourList will be 2D arraylist.
System.out.println(yourList.get(0)[0]); // This will print adc.
System.out.println(yourList.get(0)[1]); // This will print def.
System.out.println(yourList.get(0)[2]); // This will print efg.
// Similarly you can fetch other elements by yourList.get(1)[index]
What you can do is:
String str[]="adc|def|efg||hij|lmn|opq".split("||");
String str2[]=str[0].split("|");
str2 will be containing abc, def , efg
// arrays have toList() method like:
Arrays.asList(any_array);
Can hardly understand your problem...
I guess you may want to use a 2-dimenison ArrayList : ArrayList<ArrayList<String>>
String input = "adc|def|efg||hij|lmn|opq";
ArrayList<ArrayList<String>> res = new ArrayList<ArrayList<String>>();
for(String strs:input.split("||")){
ArrayList<String> strList = new ArrayList<String>();
for(String str:strs.split("|"))
strList.add(str);
res.add(strList);
}

Transform Set<Keyword> into String[]

I have an object Keyword that stores a String with the text of the keyword and a set o keywords (Set<Keyword>) that I need to transform into a String array. Is there a quick/easy way to do this or I need to iterate the set and add each keyword one by one?
EDIT:
For those asking for Keyword class:
#Entity
public class Keyword {
// ...
#Basic
private String value;
// ...
// Getters & Setters
}
Every class that implements Collection intefrace (and that includes Set) has toArray() method:
String[] array= set.toArray(new String[0]);
In case of a set that is parametrized with some other type, e.g. Set<Keyword> you would have to do something like:
Keyword[] array= set.toArray(new Keyword[0]);
String[] stringArray= new String[array.length];
for (int i=0; i<array.length; i++) {
stringArray[i]= array[i].getThatString();
}
Try this:
String[] arr = set.toArray(new String[set.size()]);
... is what I would have said, if you had a Set<Object>.
No, there is no way to directly convert a Set<Keyword> to a String[] since there is no direct relationship between Keyword and String. You will have to iterate over the set:
String[] arr = new String[set.size()];
int i = 0;
for (Keyword word : set)
arr[i++] = word.toString();
If you use Guava, you may use this:
Lists.transform(Lists.newArrayList(theSet), Functions.usingToString())
.toArray(new String[theSet.size()])
And this only scratches the surface of what Guava can actually do.
There is no specific way to do this . You can either convert Set to Object[] using set.toArray and then iterate over the array
or
iterate over the set directly
You may need to add toString() method to your Keyword class as shown below. Or you can use a separate transformer class/method.
class Keyword {
private String value;
Keyword(String v) {
this.value = v;
}
public String toString() {
return value;
}
}
.
I would say iterate the set and add each keyword one by one is your best possible strategy.
System.out.println(toStringArray(set));
.
private static String[] toStringArray(Collection<?> set) {
String[] arr = null;
if (set != null) {
arr = new String[set.size()];
int i = 0;
for (Object o : set) {
arr[i++] = o.toString();
}
}
return arr;
}
.
However if you really want, you can have a dirty workaround as shown below. Only issue here is that your keyword value cannot contain comma (,) as it is used by split() method.
String str = set.toString();
str = str.substring(1, str.length() - 1);
String[] asStringArray = str.split(",");
System.out.println(asStringArray);

Java split string from array

I have a string array that contains some information.
Example:
String [] testStringArray;
testStringArray[0]= Jim,35
Alex,45
Mark,21
testStringArray[1]= Ana,18
Megan,44
This is exactly how the information is. Now my problem is I want to make each element a seperate element in an array and I want to split it based on the \n character.
So I want
newArray[0]=Jim,35
newArray[1]=Alex,45
newArray[2]=Mark,21
newArray[3]=Ana,18
etc etc. I am aware of the split method but won't this just split each array element into a completely new array instead of combining them?
If anyone could help, it would be appreciated. Thanks
Something like this:
// Splits the given array of Strings on the given regex and returns
// the result in a single array.
public static String[] splitContent(String regex, String... input) {
List<String> list = new ArrayList<>();
for (String str : input) {
for (String split : str.split(regex)) {
list.add(split);
}
}
return list.toArray(new String[list.size()]);
}
you can call it this way:
String[] testStringArray = ...;
String[] newArray = splitContent("\n", testStringArray);
Because of the use of varargs you can also call it like this:
String[] newArray = splitContent("\n", str1, str2, str3, str4);
where strX are String variables. You can use any amount you want. So either pass an array of Strings, or any amount of Strings you like.
If you don't need the old array anymore, you can also use it like this:
String[] yourArray = ...;
yourArray = splitContent("\n", yourArray);
String[] testStringArray = new String[2];
ArrayList<String> result = new ArrayList<String>();
testStringArray[0]= "Jim,35\nAlex,45\nMark,21";
testStringArray[1]= "Jiam,35\nAleax,45\nMarak,21";
for(String s : testStringArray) {
String[] temp = s.split("\n");
for(String t : temp) {
result.add(t);
}
}
String[] res = result.toArray(new String[result.size()]);
Try This is working Code >>
String[] testStringArray = new String[2]; // size of array
ArrayList<String> result = new ArrayList<String>();
testStringArray[0]= "Jim,35\nAlex,45\nMark,21"; // store value
testStringArray[1]= "Ana,18\nMegan,44";
for(String s : testStringArray) {
String[] temp = s.split("\n"); // split from \n
for(String t : temp) {
result.add(t); // add value in result
System.out.print(t);
}
}
result.toArray(new String[result.size()]);
you can first merge the strings into one string and then use the split method for the merged string.
testStringArray[0]= Jim,35
Alex,45
Mark,21
testStringArray[1]= Ana,18
Megan,44
StringBuffer sb = new StringBuffer();
for(String s : testStringArray){
s = s.trim();
sb.append(s);
if (!s.endWith("\n")){
sb.append("\n");
}
}
String[] array = sb.toString().split("\n");
Try this. It is simple and readable.
ArrayList<String> newArray = new ArrayList<String>();
for (String s : testStringArray) {
newArray.addAll(Arrays.asList(s.split("\\n"));
}
Firstly, you can't write what you just did. You made a String array, which can only contain Strings. Furthermore the String has to be in markers "" like "some text here".
Furthermore, there can only be ONE String at one place in the array like:
newArray[0] = "Jim";
newArray[1] = "Alex";
And NOT like:
newArray[0] = Jim;
And CERTAINLY NOT like:
// Here you're trying to put 2 things in 1 place in the array-index
newArray[0] = Jim, 35;
If you wan't to combine 2 things, like an name and age you have to use 2D array - or probably better in your case ArrayList.
Make a new class with following object:
public class Person {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
And afterwards go to your class where you want to use the original array, and write:
ArrayList<Person> someNameOfTheArrayList = new ArrayList<Person>();
someNameOfTheArrayList.add(new Person("Jim", 32));
someNameOfTheArrayList.add(new Person("Alex", 22));

Categories