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);
}
Related
I have the below input string:
"["role_A","role_B","role_C"]"
I want to convert it to a list/array of strings containing all values(role_A, role_B, role_C).
I've done using the below code:
String allRoles = roles.replace("\"","").replaceAll("\\[", "").replaceAll("\\]","").split(",");
Can anyone please suggest more cleaner or better way to do it using Java8!
Existing example and ones with replacing quotes can break if there are quotes in the strings themselves. You can use JSONArray to parse it and then convert to a list if needed
String x = "[\"role_A\",\"role_B\",\"role_C\"]";
JSONArray arr = new JSONArray(x);
List<String> list = new ArrayList<String>();
for (Object one : arr) {
list.add((String)one);
}
System.out.println(list); //prints [role_A, role_B, role_C]
System.out.println(list.size()); //prints 3
json.jar can be found in the Maven repo
String s = "[\"role_A\",\"role_B\",\"role_C\"]";
String[] res = s.split("\\[")[1].split(",");
for (String str : res) {
str = str.replace("]", "").replace("\"", "");
}
Resulting array res is your desired array.
This should do the trick:
String[] arr = s.substring(2, s.length()-2).split("\",\"");
the simplest solution is using GSON or Jackson or any Json converter.
but if you want to do it in manually you can use regex to remove any symbols and split it by comma. But I suggest to use library instead, to make your life easier.
ObjectMapper mapper = new ObjectMapper();
List<String> list = mapper.readValue("[\"role_A\",\"role_B\"]",
mapper.getTypeFactory().constructCollectionType(List.class,
String.class));
One way to achieve this can be as:
List<String> roles = Stream.of(rolesStr.replaceAll("[\"\\[\\]]","").split(",")).collect(Collectors.toList());
System.out.println(roles);
output:
[role_A, role_B, role_C]
I have a String like this:
["http://www.ebuy.al/Images/dsc/17470_500_400.jpg", "http://www.ebuy.al/Images/dsc/17471_500_400.jpg"]
How can I convert it into an ArrayList of Strings?
Use Arrays#asList
String[] stringArray = { "http://www.ebuy.al/Images/dsc/17470_500_400.jpg", "http://www.ebuy.al/Images/dsc/17471_500_400.jpg"}
List<String> stringList = Arrays.asList(stringArray);
In case your string contains braces [] and double quotes "", then you should parse the string manually first.
String yourString = "[\"http://www.ebuy.al/Images/dsc/17470_500_400.jpg\", \"http://www.ebuy.al/Images/dsc/17471_500_400.jpg\"]";
String[] stringArray = yourString
.substring(1, yourString.length() - 2)
.replace('"', '\0')
.split(",\\s+");
List<String> stringList = Arrays.asList(stringArray);
Try the above if and only if you will always receive your String in this format. Otherwise, use a proper JSON parser library like Jackson.
This would be more appropriate
String jsonArr = "[\"http://www.ebuy.al/Images/dsc/17470_500_400.jpg\",
\"http://www.ebuy.al/Images/dsc/17471_500_400.jpg\"]";
List<String> listFromJsonArray = new ArrayList<String>();
JSONArray jsonArray = new JSONArray(jsonArr);
for(int i =0 ;i<jsonArray.length();i++){
listFromJsonArray.add(jsonArray.get(i).toString());
}
And don't forget to add json library
You can use simple CSV parser if you remove the first and last brackets ('[',']')
Something like this:
List<String> items = Arrays.asList(str.split("\\s*,\\s*"));
Method 1: Iterate through the array and put each element to arrayList on every iteration.
Method 2: Use asList() method
Example1:
Using asList() method
String[] urStringArray = { "http://www.ebuy.al/Images/dsc/17470_500_400.jpg", "http://www.ebuy.al/Images/dsc/17471_500_400.jpg"}
List<String> newList = Arrays.asList(urStringArray);
Example2
Using simple iteration
List<String> newList = new ArrayList<String>();
for(String aString:urStringArray){
newList.add(aString);
}
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));
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>
I have used scanner instead of string tokenizer ,, below is the piece of code...
Scanner scanner = new Scanner("Home,1;Cell,2;Work,3");
scanner.useDelimiter(";");
while (scanner.hasNext()) {
// System.out.println(scanner.next());
String phoneDtls = scanner.next();
// System.out.println(phoneDtls);
ArrayList<String> phoneTypeList = new ArrayList<String>();
if(phoneDtls.indexOf(',')!=-1) {
String value = phoneDtls.substring(0, phoneDtls.indexOf(','));
phoneTypeList.add(value);
}
Iterator itr=phoneTypeList.iterator();
while(itr.hasNext())
System.out.println(itr.next());
}
The ouput I get upon executing this...
Home
Cell
Work
As it is seen from the above code is that in the array list phoneTypeList we are finally storing the values..but the logic of finding out the value on the basisi of ',' is not that much great..that is ..
if(phoneDtls.indexOf(',')!=-1) {
String value = phoneDtls.substring(0, phoneDtls.indexOf(','));
phoneTypeList.add(value);
}
could you please advise me with some other alternative ..!! to achieve the same thing...!!thanks a lot in advance..!!
Well, since you asked if there is another way to do it then here is an alternative: You can split the string directly and do it with less code with the foreach statement:
String input = "Home,1;Cell,2;Work,3";
String[] splitInput = input.split(";");
for (String s : splitInput ) {
System.out.println(s.split(",")[0]);
}
No need to use the ArrayList<T> since you can iterate over an array as well.
could you try to split based on ',' STIRNG_VALUE.split(','); will return u an array with strings separated with , may be this helps
If i understand correctly. The problem statement is you want to maintain a list of Phone-Type-List. Like this: ["Home", "Cell", "Work"].
I suggest you keep this in a property file / config file / database which ever makes sense and load it to memory on start of you app.
If the input cannot be changed then as for the algorithm i couldn't think of a better one. Looks good.
You could use split function of string if that makes sense.
First use split on ";"
Then a split on ","
declare the arraylist outside the while loop.
try this, i have made some change for better performance too. hope you can compare and understand the change.
ArrayList<String> phoneTypeList = new ArrayList<String>();
Scanner scanner = new Scanner("Home,1;Cell,2;Work,3");
scanner.useDelimiter(";");
String phoneDtls = null;
String value = null;
while (scanner.hasNext()) {
phoneDtls = scanner.next();
if (phoneDtls.indexOf(',') != -1) {
value = phoneDtls.split(",")[0];
phoneTypeList.add(value);
}
}
Iterator itr = phoneTypeList.iterator();
while (itr.hasNext())
System.out.println(itr.next());
I have executed n got the result, check screenshot.