Split a string in java - java

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

Related

How to convert String to array/object/LIst

String str = "[[28.667949,77.287067,232,0,0.8,5],[28.667949,77.287067,232,0,0.8,5]]";
I have a String, and want to convert it into any type either in Array,List or Object except String.
Expected Output :
List/Array/Object =
[[28.667949,77.287067,232,0,0.8,5],[28.667949,77.287067,232,0,0.8,5]]
you have to do
List ls = Arrays.asList(str.replaceAll("\\[", "").replaceAll("\\]", "").split(","));
There is work around for this
1.) First replace all '[' and ']' with ""
str = str.replaceAll("[","");
str = str.replaceAll("]","");
2.)Then u can split the string with ","
which gives u an array.
String[] split = str.split(",");
If groups of data is important, here's an algo:
1. create new List<List<String>> strList
2. String [] strs= str.split("],")
3. loop each str in strs
3.1 replace all existence of "[" and "]" of str
3.2 strList.add(Arrays.asList(str.split(",")))
Hope this helps!

delete dynamic character from string

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

Java get the same String after split

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("*");
}

Parsing String Java

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]

Splitting a period-delimited string into multiple strings

I have a string
String x = "Hello.August 27th.Links.page 1";
I am wondering if I can split this string into 4 other strings based on where the period is. For example, the four other strings would be,
String a = "Hello";
String b = "August 27th";
String c = "Links";
String d = "page 1";
As you can see I basically want to extract certain parts of the string out into a new string, the place where it is extracted is based on where the period is which ends the first string and then shows where the 2nd and, etc. strings end.
Thanks in advance!
In android btw
Use String#split (note that it receives a regex as a parameter)
String x = "Hello.August 27th.Links.page 1";
String[] splitted = x.split("\\.");
Yes of course just use:
String[] stringParts = myString.split("\\.")
String x = "Hello.August 27th.Links.page 1"
String []ar=x.split("[.]");
Perhaps you can use StringTokenizer for this requirement. Here is the simple approach:
String x = "Hello.August 27th.Links.page 1";
if (x.contains(".")) {
StringTokenizer stringTokenizer = new StringTokenizer(x, ".");
String[] arrayOfString = new String[stringTokenizer.countTokens()];
int i = 0;
while (stringTokenizer.hasMoreTokens()) {
arrayOfString[i] = stringTokenizer.nextToken();
i++;
}
System.out.println(arrayOfString[0]);
System.out.println(arrayOfString[1]);
System.out.println(arrayOfString[2]);
System.out.println(arrayOfString[3]);
}
You are done. :)

Categories

Resources