I got a String:
["4fd1cf1783353a15415","4ffecf87fcc40d110a965626"]
or
["4fd5f684815345","4fd6ef3e60a676854651","4fd83c33c19164512153"]
And I'd like to store every id (eg. 4fd5f684815345, 4fd6ef3e60a676854651, 4fd83c33c19164512153...) in a independant String (or ArrayList).
How to parse it, because the String can be dynamic (1,2,3 values or more)?
OR JSON Array Parsing:
My JSON
"idCards":[
"4fc52f95egvt418541515",
"4fd1d05454151541545115"
],
A part of my code:
msg3 = (JSONArray) myobject.get("idCards");
System.out.println(msg3.toJSONString());
The result:
[4fc52f95egvt418541515","4fd1d05454151541545115"]
I'd like this 2 values in 2 differents String.
Many thanks for your help!
It would appear to be that this could be a JSON String. In which case, you may make use of a Java JSON Library to help you parse that into Java native objects.
http://www.json.org/
http://code.google.com/p/google-gson/
String data = "[\"4fd5f684815345\",\"4fd6ef3e60a676854651\",\"4fd83c33c19164512153\"]";
// parse JSON String to JSON Array
JsonArray array = (JsonArray) (new JsonParser()).parse(data);
// build a Java ArrayList
List<String> stringList = new ArrayList<String>();
// for each item in JsonArray, add to Java ArrayList
for (int i = 0; i < array.size(); i++) {
stringList.add((array.get(i)).getAsString());
}
I fully agree with the JSON answers, but if this is a one-off hack, you could just do this:
String input = "[\"4fd5f684815345\",\"4fd6ef3e60a676854651\",\"4fd83c33c19164512153\"]";
input = input.replace("[", "");
input = input.replace("]", "");
input = input.replace("\"", "");
String[] parts = input.split(",");
I make a number of assumptions here:
Assume no spaces before and after the delimiting [, ], ,
Assume no , and " character in the Strings you want to extract
input.substring(1, input.length() - 1).replaceAll("\\\"", "").split(",");
Or if you don't want to mess with regular expression (replaceAll function works with regular expression), then you can use replace method:
input.substring(1, input.length() - 1).replace("\"", "").split(",");
Due to the assumptions above, this answer is very brittle. Consider using JSON parser if the data is really JSON.
String str = "[\"4fd5f684815345\",\"4fd6ef3e60a676854651\",\"4fd83c33c19164512153\"]";
String strArry[] = null;
if(str.trim().length() > 0){
str = str.substring(1 , str.length()-1).replaceAll("\\\"", "");
strArry = str.split(",");
}
If s is the input string, it can just be as simple as
String[] idArray = s.replaceAll("[\\[\\]\"]", "").split(",");
it would be more secure (because ',' may be a decimal separator) to split with ("\",\""), and not remove trailing " in replaceAll, here subtring do not parse all the string :
final String str = "[\"4fd5f684815345\",\"4fd6ef3e60a676854651\",\"4fd83c33c19164512153\"]";
final String strArray[] = str.substring(2, str.length() - 2).split("\",\"");
final ArrayList<String> al = new ArrayList<String>();
for (final String string : strArray) {
al.add(string);
System.out.println(string);
}
System.out.println(al);
for (final String string : strArray) {
System.out.println(string);
}
Output :
4fd5f684815345
4fd6ef3e60a676854651
4fd83c33c19164512153
[4fd5f684815345, 4fd6ef3e60a676854651, 4fd83c33c19164512153]
Related
I have a JSON object
{"name":["123-abc","234-bca","567-yuio"]}
with unknown length. I need to store it as a string and split the commas and iterate to print only the value i.e 123-abc should be printed first then 234-bca etc..
-> Input: {"name":["123-abc","234-bca","567-yuio"]}
-> Output: 123-abc
234-bca
567-yuio
Please help me out as I'm new to coding. Thank You
You can try this:
JSONObject json = (JSONObject) object;
String input = json.get("name");
//String input = "\"123-abc\",\"234-bca\",\"567-yuio\"";
String[] strArray = input.split(",");
for (String string : strArray)
System.out.println(string.replace("\"", ""));
Here object is where you stored your JSON object.
At first, you have to split the string at the commas and you have to iterate over the split list, using e.g. a for-loop:
for (String val : input.substring(1, input.length() - 1).split(",")) {
System.out.println(val.replace("\"", ""));
}
You shouldn't need to store it as a string, you can actually just pull out that array from the JSON object and iterate over it.
JSON obj = new JSONObject(); //Get/store your data however you'd like. I will call it obj
String[] name = obj.get( "name" );
for (int i = 0; i < name.length; i++) { //Loop through your array and output each part
System.out.println( name[ i ] );
}
If you need to convert the obj to a string use can use the .toString() function. But the above should be the easiest way to output that data.
How to transform a string with this format into a list?
[[["Census_county_divisions","Populated_places_in_the_United_States","Populated_places_by_country","Geography_by_country","Geography_by_place","Geography","Main_topic_classifications"]],[["example","text","thanks"]],[["name","surname","age"]]]
From that string I would like to have 3 lists:
List 1:
"Census_county_divisions","Populated_places_in_the_United_States","Populated_places_by_country","Geography_by_country","Geography_by_place","Geography","Main_topic_classifications"
List 2:"example","text","thanks"
List 3:"name","surname","age"
I have tried different approachs do process this string, with split, with method StringUtils.substringBetween, with indexOf, with regex, with Json Parser.... I always get an error, is it an easier way out??
Comments: I don't see this string as a Json format, since the Json format would be "name":"John", If I'm wrong, please let me know how I could process it as a Json....
I have tried also with JsonParser and had the Exception in thread "main" java.lang.IllegalStateException: Not a JSON Object:
[[["Census_county_divisions","Popula
I write this code:
remove the [[[,]]] strings
replace the ]],[[ for | character
split the string
///The String to convert
String arg = "[[[\"Census_county_divisions\",....
[[\"example\",\"text\",\"thanks\"]],[[\"name\",\"surname\",\"age\"]]]";
System.out.println(arg);
////Replace
arg = arg.replace("[[[", "");
arg = arg.replace("]],[[", "|");
arg = arg.replace("]]]", "");
System.out.println(arg);
////Split
String[] array=arg.split("\\|");
List<String> list = Arrays.asList(array);
///Verify
for(String s: list) {
System.out.println(s);
}
Regards
This worked for me. I only trimmed the start and end character set and then split it into 3 different strings which yielded the lists.
str = new StringBuilder(str).replace(0, 4, "")
.reverse().replace(0, 4, "")
.reverse()
.toString();
String[] arr1 = str.split("\"\\]\\],\\[\\[\"");
List<String> list1 = Arrays.asList(arr1[0]
.split("\",\""));
List<String> list2 = Arrays.asList(arr1[1]
.split("\",\""));
List<String> list3 = Arrays.asList(arr1[2]
.split("\",\""));
Maybe you could use Regex to extract everything inside the "[[" "]]" and trimming the "[" and "]" at the start and the end of each group. After that, you could split the result and put it into a List.
Here a simple example:
List<List<String>> lists = new ArrayList<>();
String string = "[[[\"Census_cunty_divisions\",\"Populated_places_in_the_United_States\",\"Populated_places_by_country\",\"Geography_by_country\",\"Geography_by_place\",\"Geography\",\"Main_topic_classifications\"]],[[\"example\",\"text\",\"thanks\"]],[[\"name\",\"surname\",\"age\"]]]";
Pattern pattern = Pattern.compile("\\[\\[(.*?)\\]\\]");
Matcher matcher = pattern.matcher(string);
String proccesed;
while (matcher.find()) {
for (int i = 1; i <= matcher.groupCount(); i++) {
proccesed = StringUtils.strip(matcher.group(i), "[");
proccesed = StringUtils.strip(proccesed, "]");
lists.add(Arrays.asList(proccesed.split(",")));
}
}
int i = 0;
for(List<String> stringList : lists){
System.out.printf("List # %s \n", i);
for(String elementOfList:stringList){
System.out.printf("Element %s \n", elementOfList);
}
i++;
}
Here you will have a dynamic list depending on the initial String.
I've used the org.apache.commons commons-text library to strip the matches.
I hope it's useful.
I have a string containing numbers separated with ,. I want to remove the , before the first character.
The input is ,1,2,3,4,5,6,7,8,9,10, and this code does not work:
results.replaceFirst(",","");
Strings are immutable in Java. Calling a method on a string will not modify the string itself, but will instead return a new string.
In order to capture this new string, you need to assign the result of the operation back to a variable:
results = results.replaceFirst(",", "");
Try this
String str = ",1,2,3,4,5,6,7,8,9,10";
str = str .startsWith(",") ? str .substring(1) : str ;
System.out.println("output"+str); // 1,2,3,4,5,6,7,8,9,10
you can also do like this ..
String str = ",1,2,3,4,5,6,7,8,9,10";
String stre = str.replaceFirst("^,", "");
Log.e("abd",stre);
Try this
String str = ",1,2,3,4,5,6,7,8,9,10";
if(Objects.nonNull(str) && str.startsWith(",")){
str = str.substring(1, str.length());
}
it will remove , at first position
In Java if you want to split a String by a char or a String you can do that by the split method as follow:
String[] stringWords = myString.split(" ");
But let's say i want now to create a new String using the strings in stringWords using the char * between them. Is there any solutions to do it without for/while instructions?
Here is a clear example:
String myString = "This is how the string should be";
String iWant = "This*is*how*the*string*should*be";
Somebody asks me to be more clear why i don't want just to use replace() function. I don't want to use it simply because the content of the array of strings (array stringWords in my example) changes it's content.
Here is an example:
String myString = "This is a string i wrote"
String[] stringWords = myString.split(" ");
myAlgorithmFucntion(stringWords);
Here is an example of how tha final string changes:
String iWant = "This*is*something*i*wrote*and*i*don't*want*to*do*it*anymore";
If you don't want to use replace or similar, you can use the Apache Commons StringUtils:
String iWant = StringUtils.join(stringWords, "*");
Or if you don't want to use Apache Commons, then as per comment by Rory Hunter you can implement your own as shown here.
yes there is solution to, split String with special characters like '*','.' etc. you have to use special backshlas.
String myString = "This is how the string should be";
iWant = myString.replaceAll(" ","*"); //or iWant = StringUtils.join(Collections.asList(myString.split(" ")),"*");
iWant = "This*is*how*the*string*should*be";
String [] tab = iWant.split("\\*");
Try something like this as you don't want to use replace() function
char[] ans=myString.toCharArray();
for(int i =0; i < ans.length; i++)
{
if(ans[i]==' ')ans[i]='*';
}
String answer=new String(ans);
Try looping the String array:
String[] stringWords = myString.split(" ");
String myString = "";
for (String s : stringWords){
myString = myString + "s" + "*";
}
Just add the logic to deleting the last * of the String.
Using StringBuilder option:
String[] stringWords = myString.split(" ");
StringBuilder myStringBuilder = new StringBuilder("");
for (String s : stringWords){
myStringBuilder.append(s).append("*");
}
I am getting this string from a program
[user1, user2]
I need it to be splitted as
String1 = user1
String2 = user2
You could do this to safely remove any brackets or spaces before splitting on commas:
String input = "[user1, user2]";
String[] strings = input.replaceAll("\\[|\\]| ", "").split(",");
// strings[0] will have "user1"
// strings[1] will have "user2"
Try,
String source = "[user1, user2]";
String data = source.substring( 1, source.length()-1 );
String[] split = data.split( "," );
for( String string : split ) {
System.out.println(string.trim());
}
This will do your job and you will receive an array of string.
String str = "[user1, user2]";
str = str.substring(1, str.length()-1);
System.out.println(str);
String[] str1 = str.split(",");
Try the String.split() methods.
From where you are getting this string.can you check the return type of the method.
i think the return type will be some array time and you are savings that return value in string . so it is appending [ ]. if it is not the case you case use any of the methods the users suggested in other answers.
From the input you are saying I think you are already getting an array, don't you?
String[] users = new String[]{"user1", "user2"};
System.out.println("str="+Arrays.toString(str));//this returns your output
Thus having this array you can get them using their index.
String user1 = users[0];
String user2 = users[1];
If you in fact are working with a String then proceed as, for example, #WhiteFang34 suggests (+1).