I need to get string from between two characters. I have this
S= "10:21:35 |Manipulation |Mémoire centrale |MAJ Registre mémoire"
and it have to return 4 strings each in a variable:
a=10:21:35
b=Manipulation
c=Mémoire centrale
d=MAJ Registre mémoire
There's String#split
. Since it accepts a regular expression string, and |
is a special character in regular expressions, you'll need to escape it (with a backslash). And since \
is a special character in Java string literals, you'll need to escape it, too, which people sometimes find confusing. So given:
String S = "10:21:35 |Manipulation |Mémoire centrale |MAJ Registre mémoire";
then
String[] parts = S.split("\\|");
int index;
for (index = 0; index < parts.length; ++index) {
System.out.println(parts[index]);
}
would output
10:21:35
Manipulation
Mémoire centrale
MAJ Registre mémoire
(With the trailing spaces on the first three bits; trim
those if necessary.)
String s = " 10:21:35 | Manipulation | Mémoire centrale | MAJ Registre mémoire ";
String[] split = s.trim().split("\\s*\\|\\s*",-1); //trim and split
Alternatively, org.apache.commons.lang.StringUtils has about 14 variants of the split() method.
If the length of each column is varient, use the examples given here with the split
method.
However, if you have a fixed-sized file format substring
will be a much better option. If you look at the implementation of substring
(Java 5 and above if I recall correctly) - you can see that it has an O(1) to create the new strings, whereas split
uses a regex which is time consuming.
You probably want this:
String[] s = "10:21:35 |Manipulation |Mémoire centrale |MAJ Registre mémoire".split("\\|");
There's also method trim()
which removes trailing spaces from the strings.
Like in other answers I suggest you using split() method to separate your string but remeber to use trim if you won't have spaces after parts, like this:
S= "10:21:35 |Manipulation |Mémoire centrale |MAJ Registre mémoire"
String splitted[] = S.split("\\|");
String a = splitted[0].trim();
String b = splitted[1].trim();
...
You can also use string.substring and get the required output as
string a =s.substring(0,8)
Like this u can assign for the one you want