[英]Get string from between two characters
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: 并且必须在一个变量中分别返回4个字符串:
a=10:21:35
b=Manipulation
c=Mémoire centrale
d=MAJ Registre mémoire
There's String#split
. 有
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. 而且,由于
\\
是Java字符串字面特殊字符,你需要逃脱它 ,也一样,人们有时会感到迷惑。 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.) ( 在前三位保留尾随空格;如有必要,对它们进行
trim
。)
String s = " 10:21:35 | Manipulation | Mémoire centrale | MAJ Registre mémoire ";
String[] split = s.trim().split("\\s*\\|\\s*",-1); //trim and split
另外,org.apache.commons.lang.StringUtils具有split()方法的大约14个变体。
If the length of each column is varient, use the examples given here with the split
method. 如果每列的长度是可变的,请使用此处使用
split
方法给出的示例。
However, if you have a fixed-sized file format substring
will be a much better option. 但是,如果您使用固定大小的文件格式,则
substring
将是更好的选择。 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. 如果您查看
substring
的实现(如果我没记错的话,请参见Java 5及更高版本)-您会看到它具有O(1)来创建新字符串,而split
使用正则表达式很耗时。
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. 还有一个
trim()
方法可以从字符串中删除尾随空格。
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: 像在其他答案中一样,我建议您使用split()方法来分隔字符串,但如果零件后没有空格,请记住使用trim,例如:
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.substring并获取所需的输出为
string a =s.substring(0,8)
Like this u can assign for the one you want 这样你就可以分配你想要的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.