Get string from between two characters

2020-04-19 05:52发布

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

7条回答
来,给爷笑一个
2楼-- · 2020-04-19 06:10

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

查看更多
Animai°情兽
3楼-- · 2020-04-19 06:12

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();
...
查看更多
爱情/是我丢掉的垃圾
4楼-- · 2020-04-19 06:13

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.

查看更多
我想做一个坏孩纸
5楼-- · 2020-04-19 06:15

Alternatively, org.apache.commons.lang.StringUtils has about 14 variants of the split() method.

查看更多
时光不老,我们不散
6楼-- · 2020-04-19 06:16

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.

查看更多
老娘就宠你
7楼-- · 2020-04-19 06:18

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

查看更多
登录 后发表回答