how to split a string twice and add to ArrayList - java

I have a single string as follows
one two
three
four
I would like to split this into an arrayList so that I can get
String[] g = [one,two,three,four]
I think I need to split by newline and by space but something so simple is defeating me
I have tried:
String [] bilbo=null;
List<String> temp=new ArrayList<String>();
bilbo=g.split("\\n|\\r");
for (String d:bilbo) {
if (d!="") {
if (d.matches("\\s")) {
dd = d.split("\\s");
for (String a : dd) {
temp.add(a.trim());
}
} else {
temp.add(d.trim());
}
}
}

Instead of splitting with "\n|\r", you could simply split with "\\s+", which will cover spaces and new lines:
ArrayList<String> list = Arrays.asList(g.split("\\s+"));

Related

How to convert string array literal to array list with no quotes

Simple scenario but finding difficult to finish off -
my string is -
String ipAdd = "["2.2.2.2","1.1.1.1","6.6.6.6","4.4.4.4"]"
I want to have all elements in an array list. How can I do that?
I try pattern matching for IP and all, not working and by using split function, it includes quotes and bracket.
Using replaceAll() (to remove braces) and split() (to split based on comma) should work :
public static void main(String... args) throws Exception {
String ipAdd = "[\"2.2.2.2\",\"1.1.1.1\",\"6.6.6.6\",\"4.4.4.4\"]";
List<String> list = Arrays.asList(ipAdd.replaceAll("\\[|\\]", "").split(","));
for (String s : list){
System.out.println(s);
}
}
O/P :
"2.2.2.2"
"1.1.1.1"
"6.6.6.6"
"4.4.4.4"
The following code maybe fulfill your requirement:
public static void main(String[] args) {
String st = "[\"2.2.2.2\",\"1.1.1.1\",\"6.6.6.6\",\"4.4.4.4\"]";
String patternString1 = "(\\d\\.\\d\\.\\d\\.\\d)";
Pattern pattern = Pattern.compile(patternString1);
Matcher matcher = pattern.matcher(st);
ArrayList<String> list = new ArrayList<>();
while(matcher.find()) {
list.add(matcher.group(1));
}
for (String item : list) {
System.out.println("" + item);
}
}
You can use regular expression with capturing groups to extract the IP from the string. (refer to https://docs.oracle.com/javase/tutorial/essential/regex/groups.html)

Comparison of two lists in java using for loop

I have two list word containing words (word is a copy of the list words) and existingGuesses containing characters and I want to compare them (means compare whether each character is present in the list word or not) by iterating through a for loop. Can anybody suggest me how to do the comparison?
public List<String> getWordOptions(List<String> existingGuesses, String newGuess)
{
List<String> word = new ArrayList<String>(words);
/* String c = existingGuesses.get(0);
ListIterator<String> iterator = word.listIterator();
while(iterator.hasNext()){
if(word.contains(c))
{
word.remove(c);
}
}*/
for(String temp: word){
for(String cha: existingGuesses){
}
}
return null;
}
You can check for the guesses in words like this by using the List#contains(Object).
for(String myGuess: existingGuesses){
if(word.contains(myGuess)) {
// Do what you want
}
}
How about the following O(N) complexity code
public List<String> getWordOptions(List<String> existingGuesses, String newGuess) {
List<String> word = new ArrayList<String>(words);
for (String cha : existingGuesses) {
if (word.contains(cha)) {
word.remove(cha);
}
}
return null;
}
If you want to compare them and remove them if its there,
Then You can use the List#removeAll(anotherlist)
Removes from this list all of its elements that are contained in the specified collection (optional operation).
(Got clue from word.remove(c);) from your commented code.
You can use Collection.retainAll:
List<String> word=new ArrayList<String>();//fill list
List<String> existingGuesses=new ArrayList<String>();//fill list
List<String> existingWords=new ArrayList<String>(word);
existingWords.retainAll(existingGuesses);
//existingWords will only contain the words present in both the lists
System.out.println(existingWords);

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

Concating a String from an arraylist

I have an array list ArrayList<String> firstname; In this I am storing n number of names which have been parsed from an xml file.
Now from this ArrayList I need to take all the names and store it in a Single separate
String names along with a slash(/) between of each names.
For eg firstname= {a, c,f,g,h,j,k}
Now i want it to be as follows names= a/c/f/g/h/j/k
So far I have created a for loop to get values from the ArrayList by its size
String names;
for(int k=0;k<Appconstant.firstname.size();k++) {
names = Appconstant.firstname.get(k);
}
String names = TextUtils.join("/", Appconstant.firstname);
String names;
for(int k=0;k<Appconstant.firstname.size();k++)
{
if(k<=Appconstant.firstname.size()-1)
names += Appconstant.firstname.get(k)+"/";
else
names += Appconstant.firstname.get(k)
}
Though you should be using a StringBuilder instead.
Off the top of my head, but something like this:
StringBuilder builder = new StringBuilder();
for(String name : firstname)
{
builder.append(name).append('/');
}
// Remove last '/'
builder.deleteCharAt(builder.length()-1);
StringBuilder myStrBuilder = null;
for(String aName:yourNameList)
{
myStrBUilder.append(aName+"/");
}
myStrBuilder.deleteCharAt(myStrBUilder.length()-1)

Complex string split in Java

Consider the following String :
5|12345|value1|value2|value3|value4+5|777|value1|value2|value3|value4?5|777|value1|value2|value3|value4+
Here is how I want to split string, split it with + so I get this result :
myArray[0] = "5|12345|value1|value2|value3|value4";
myArray[1] = "5|777|value1|value2|value3|value4?5|777|value1|value2|value3|value4";
if string has doesn't contain char "?" split it with "|" and continue to part II, if string does contain "?" split it and for each part split it with "|" and continue to part II.
Here is part II :
myObject.setAttribute1(newString[0]);
...
myObject.setAttribute4(newString[3]);
Here what I've got so far :
private static String input = "5|12345|value1|value2|value3|value4+5|777|value1|value2|value3|value4?5|777|value1|value2|value3|value4+";
public void mapObject(String input){
String[] myArray = null;
if (input.contains("+")) {
myArray = input.split("+");
} else {
myArray = new String[1];
myArray[0] = input;
}
for (int i = 0; i < myArray.length; i++) {
String[] secondaryArray = null;
String[] myObjectAttribute = null;
if (myArray[i].contains("?")) {
secondaryArray = temporaryString.myArray[i].split("?");
for (String string : secondaryArray) {
myObjectAttribute = string.split("\\|");
}
} else {
myObjectAttribute = myArray[i].toString().split("\\|");
}
myObject.setAttribute1(myObjectAttribute[0]);
...
myObject.setAttribute4(myObjectAttribute[3]);
System.out.println(myObject.toString());
}
Problem :
When I split myArray, going trough for with myArray[0], everything set up nice as it should.
Then comes the myArray[1], its split into two parts then the second part overrides the value of the first(how do I know that?). I've overridden toString() method of myObject, when I finish I print the set values so I know that it overrides it, does anybody know how can I fix this?
I'm not quite sure what the intention is here, but in this snippet of code
secondaryArray = temporaryString.split("?");
for (String string : secondaryArray) {
myObjectAttribute = string.split("\\|");
}
if secondaryArray has two elements after the split operation, you are iterating over each half and re-assigning myObjectAttribute to the output of string.split("\|") each time. It doesn't matter what is in the first element of secondaryArray, as after this code runs myObjectAttribute is going to contain the result of split("\\|") on the last element in the array.
Also, there is no point in calling .toString() on a String object as you do in temporaryString = myArray[i].toString().
The code doesn't seem to be able to handle the possible expansion of strings in the secondary case. To make the code clearer, I would use a List rather than array.
private static String input = "5|12345|value1|value2|value3|value4+5|777|value1|value2|value3|value4?5|777|value1|value2|value3|value4+";
private void split(List<String> input, List<String> output, String split) {
for (String s: input) {
if (s.contains(split))
{
output.addAll(Arrays.asList(s.split(Pattern.quote(split)));
}
else
output.add(s);
}
}
public void mapObject(String input) {
List<String> inputSrings = new ArrayList<String>();
List<String> splitPlus = new ArrayList<String>();
inputStrings.add(input);
split(inputStrings, splitPlus);
List<String> splitQuest = new ArrayList<String>();
split(splitPlus, splitQuest, "?");
for (String s: splitQuest) {
// you can now set the attributes from the values in the list
// splitPipe
String[] attributes = s.split("\\|");
myObject.setAttribute1(attributes[0]);
....
myObject.setAttribute4(attributes[3]);
System.out.println(myObject);
}
}

Categories