[英]How to isolate a component of a String?
I have a method that returns a String
. 我有一个返回String
的方法。 That string called contact
is made of multiple smaller strings. 称为contact
字符串由多个较小的字符串组成。 Those smaller strings were parameters to that method. 那些较小的字符串是该方法的参数。
exemple : 例如:
String contact = id + " " + name + " " + telNum;
return contact;
Now I have another method that takes contact
as a parameter but that needs to return ONLY name. 现在我有另一种方法,它将contact
作为参数但需要返回ONLY名称。
So my question is how can I isolate that smaller string name
from the whole string contact? 所以我的问题是如何从整个字符串联系人中隔离出较小的字符串name
?
Use 使用
String[] splits = contact.split(" ");
String name = splits[1];
The answer of Viswanath shows how to retrieve the name from the string using string functions. Viswanath的答案显示了如何使用字符串函数从字符串中检索名称。
As an alternative you could consider to create a Contact class which holds the information: 作为替代方案,您可以考虑创建一个包含信息的Contact类:
public class Contact {
public String id;
public String name;
public String tel;
public String toString() { return id + " " + name + " " + telNum; }
}
and then pass a Contact object around instead of the string which represents the contact . 然后传递一个Contact对象而不是代表联系人的字符串。
If id and telNum are two integer/long values you can do something like 如果id和telNum是两个整数/长值,你可以做类似的事情
int startIndex = contact.indexOf(" ");
int endIndex = contact.lastIndexOf(" ");
String name = contact.substring(startIndex, endIndex).trim();
It should be easier if your string has separators, like comma. 如果你的字符串有分隔符,比如逗号,应该会更容易。
Ex.: String contact = id + ", " + name + ", " + telNum;
In this case you could do the same of above but searching the index of "," or of ", ". 在这种情况下,您可以执行上述相同操作,但搜索“,”或“,”的索引。
如果您的ID只有号码,而电话号码以+
或任何数字开头,那么您可以轻松地从中获取名称。
String name = contact.substring(contact.indexOf(" ", 0)+1, contact.indexOf(" ", contact.indexOf(" ", 0)+1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.