Java 在android中拆分一个字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32516565/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Split a string in android
提问by Nguyen Quoc
I have a string after scan QR code is "MAT:TO:My address email;SUB:My title;BODY:My content;;". How to split address email, your title and your content from string this? Thank you all everyone!
扫描二维码后我有一个字符串是“MAT:TO:我的地址电子邮件;SUB:我的标题;BODY:我的内容;;”。如何从字符串中拆分地址电子邮件、您的标题和您的内容?谢谢大家!
采纳答案by Nithinlal
Java version
爪哇版
String s = "MAT:TO:My address email;SUB:My title;BODY:My content;;";
String[] arrayString = s.split(";");
String email = arrayString[0];
String title = arrayString[1];
String body = arrayString[2];
email= email.substring(email.indexOf("MAT:TO:") + 7, email.length());
title= title.substring(title.indexOf("SUB:") + 4, title.length());
body= body.substring(body.indexOf("BODY:") + 5, body.length());
Especially Android official is used kotlin version:
尤其是Android官方用的是kotlin版本:
val s = "MAT:TO:My address email;SUB:My title;BODY:My content;;"
val arrayString = s.split(";").toTypedArray()
var email = arrayString[0]
var title = arrayString[1]
var body = arrayString[2]
email = email.substring(email.indexOf("MAT:TO:") + 7, email.length)
title = title.substring(title.indexOf("SUB:") + 4, title.length)
body = body.substring(body.indexOf("BODY:") + 5, body.length)
回答by Marko
Try using the split()method.
尝试使用split()方法。
If you want to split by ";"
如果你想用“ ;”分割
String[] arrayString = string.split(";");
In your case you would get
在你的情况下,你会得到
["MAT:TO:My address email", "SUB:My title", "BODY:My content"]
and then split by ":" or the other way around, whichever better suits you.
然后用“ :”或相反的方式拆分,以更适合您的为准。
String email = arrayString[0].split(":")[2];
String title = arrayString[1].split(":")[1];
String body = arrayString[2].split(":")[1];
This is a bad way to do it, not very safe.
这是一个糟糕的方法,不是很安全。
Or you could use string.substring(int startIndex, int endIndex)
.
或者你可以使用string.substring(int startIndex, int endIndex)
.