My problem is I have a string like this
String text="UWU/CST/13/0032 F"
I want this to split by / and white spaces and put into a array.So finally the array indexes should include following
UWU,
CST,
13,
0032,
F
text.split("[/ ]"), or text.split("[/ ]", -1) if you want trailing empty tokens to be returned.
Use the string.split(separator) method that takes a String (regex expression) as an argument. Here is the documentation. http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)
If you have:
String text = "UWU/CST/13/0032 F";
You can separate it by the white space first, splitting it into an array of two Strings, and then split the first String in the array by "/".
String text = "UWU/CST/13/0032 F";
String[] array = text.split(" ");
String[] other = array[0].split("/");
for (String e : array) System.out.println(e);
for (String e : other) System.out.println(e);
This code outputs:
UWU/CST/13/0032
F
UWU
CST
13
0032
Regular expressions can be used in Java to split Strings using the String.split(String) method.
For you particular situation, you should split the string on the regular expression "(\s|/)". \s matches white space while / literally matches a forward slash.
The final code for this would be:
String[] splitString = text.split("(\\s|/)");
Related
I have to separate a string into an array that may contain empty spaces, for example,
|maria|joao|fernando||
but it is ignored when you have space at the end of the line
I am using this regex split("\\|")
It should be like it: maria,joao,fernando,null
but stays like this: maria,joao,fernando
You can use:
String str = "|maria|joao|fernando||";
String[] tokens = str.replaceAll("^[|]|[|]$", "").split("[|]", -1));
//=> [maria, joao, fernando, ""]
Steps:
Replace starting and ending | using replaceAll method to get maria|joao|fernando| as input to split.
Then split it using split method with 2nd parameter as -1 to return empty tokens as well.
You only need to add double backslashes to you split string
String s = "|maria|joao|fernando||";
String [] st =s.split("\\|");
for (String string : st) {
System.out.print(string+",");
}
Java 8 solution
List<String> params = Pattern
.compile("\\|")
.splitAsStream("|maria|joao|fernando||")
.filter(e -> e.trim().length() > 0) // Remove spaces only or empty strings
.collect(Collectors.toList());
how to remove multiple token from string array in java by split along with [ ]
String Order_Menu_Name= [pohe-7, puri-3];
String [] s2=Order_Menu_Name.split("-|,");
int j = 0;
//out.println("s2.length "+s2.length);
while(j<s2.length){ }
and expected output should be each value separate.
e,g pohe 7 puri 3
Your question is not clear. Assuming that your string contains "pohe-7, puri-3" you can split them using a separator such as "," or "-" or whitespace. See below.
String Order_Menu_Name= "[pohe-7, puri-3]";
To remove "[" and "]" from the above String. you can use Java's replace method as follow:
Order_Menu_Name = Order_Menu_Name.replace("[", "");
Order_Menu_Name = Order_Menu_Name.replace("]", "");
You can replace the above two lines with one using regex expression that matches [....] if you wish to.
After you removed the above characters then you can split your string as follow.
String[] chunks = Order_Menu_Name.split(",");
i = 0;
while(chunks.length) {
System.out.println(chunks[i]);
i++;
}
You can pass one or two params to the Java split() method, one being the regex expression that defines the pattern to be found and the second argument is limit, specifying how many chunks to return, see below:
public String[] split(String regex, int limit)
or
public String[] split(String regex)
For example
String Str = new String("Welcome-to-Stackoverflow.com");
for (String retval: Str.split("-", 3)){
System.out.println(retval);
}
When splitting the above Str using seperator "-" you should get 3 chunks of strings as follow:
Welcome
to
Stackoverflow.com
If you pass the split function a limit of 2 instead of three then you get the following:
Welcome
to-Stackoverflow.com
Notice above "to-Stckoverflow.com" is returned as is because we limited the chunks to 2.
I have issues in using java string tokenizer:
String myString = "1||2||3|||4";
StringTokenizer stp = new StringTokenizer(myString, "||");
while (stp.hasMoreTokens()) {
System.out.println(stp.nextToken());
}
actual output : [1,2,3,4]
expected output : [1,2,3,'|4']
Could any one help me on the same
Try this..
String myString = "1||2||3|||4";
String[] s=myString.split("\\|\\|");
for (String string : s) {
System.err.println(string);
}
I think you cannot do anything because it's how StringTokenizer works (you can put returnDelims true and remove it manually but it's more hard than look sometimes)
String myString = "1||2||3|||4";
String[] tokens = myString.split("\\|\\|");
for(String token : tokens)
{
System.out.println(token);
}
You can use split which does what you want.
Output:
1
2
3
|4
It is recommended to use the split method of the String class for doing this since StringTokenizer matches the given string and split takes a regular expression. I would use this:
String[] splitStr = myString.split("[|]{2}");
This matches every time the regular expression [|] (a single pipe) is matched twice in a row.
You are maybe thinking of String.split, as this splits on a delimiter string.
A StringTokenizer takes the delimiter string and recognizes all characters in it as a delimiter. So in fact you redundantly specified the "|" character a second time.
Using the split function is what you maybe wanted:
System.out.println(Arrays.toString("1||2||3|||4".split("\\|\\|")));
This produces
[1, 2, 3, |4]
take a look this is an easy solution:
StringTokenizer stp = new StringTokenizer(myString, "|");
while (stp.hasMoreTokens()) {
System.out.println(stp.nextToken());
}
I'm using String.split() to divide some Strings as IPs but its returning an empty array, so I fixed my problem using String.substring(), but I'm wondering why is not working as intended, my code is:
// filtrarIPs("196.168.0.1 127.0.0.1 255.23.44.1 100.168.100.1 90.168.0.1","168");
public static String filtrarIPs(String ips, String filtro) {
String resultado = "";
String[] lista = ips.split(" ");
for (int c = 0; c < lista.length; c++) {
String[] ipCorta = lista[c].split("."); // Returns an empty array
if (ipCorta[1].compareTo(filtro) == 0) {
resultado += lista[c] + " ";
}
}
return resultado.trim();
}
It should return an String[] as {"196"."168"."0"."1"}....
split works with regular expressions. '.' in regular expression notation is a single character. To use split to split on an actual dot you must escape it like this: split("\\.").
Use
String[] ipCorta = lista[c].split("\\.");
in regular expressions the . matches almost any character.
If you want to match the dot you have to escape it \\..
Your statement
lista[c].split(".")
will split the first String "196.168.0.1" by any (.) character, because String.split takes a regular expression as argument.
However, the point, why you are getting an empty array is, that split will also remove all trailing empty Strings in the result.
For example, consider the following statement:
String[] tiles = "aaa".split("a");
This will split the String into three empty values like [ , , ]. Because of the fact, that the trailing empty values will be removed, the array will remain empty [].
If you have the following statement:
String[] tiles = "aaab".split("a");
it will split the String into three empty values and one filled value b like [ , , , "b"]
Since there are no trailing empty values, the result remains with these four values.
To get rid of the fact, that you don't want to split on every character, you have to escape the regular expression like this:
lista[c].split("\\.")
String.split() takes a regular expression as parameter, so you have to escape the period (which matches on anything). So use split("\\.") instead.
THis may help you:
public static void main(String[] args){
String ips = "196.168.0.1 127.0.0.1 255.23.44.1 100.168.100.1 90.168.0.1";
String[] lista = ips.split(" ");
for(String s: lista){
for(String s2: s.split("\\."))
System.out.println(s2);
}
}
Quick example:
public class Test {
public static void main(String[] args) {
String str = " a b";
String[] arr = str.split("\\s+");
for (String s : arr)
System.out.println(s);
}
}
I want the array arr to contain 2 elements: "a" and "b", but in the result there are 3 elements: "" (empty string), "a" and "b". What should I do to get it right?
Kind of a cheat, but replace:
String str = " a b";
with
String[] arr = " a b".trim().split("\\s+");
The other way to trim it is to use look ahead and look behind to be sure that the whitespace is sandwiched between two non-white-space characters,... something like:
String[] arr = str.split("(?<=\\S)\\s+(?=\\S)");
The problem with this is that it doesn't trim the leading spaces, giving this result:
a
b
but nor should it as String#split(...) is for splitting, not trimming.
The simple solution is to use trim() to remove leading (and trailing) whitespace before the split(...) call.
You can't do this with just split(...). The split regex is matching string separators; i.e. there will necessarily be a substring (possibly empty) before and after each matched separator.
You can deal with the case where the whitespace is at the end by using split(..., 0). This discards any trailing empty strings. However, there is no equivalent form of split for discarding leading empty strings.
Instead of trimming, you could just add an if to check if a string is empty or not.