[英]string manipulation in java, getting first characters
假设我有一个字符串,其格式为“name_surname”。 我的意思是有 2 个动态部分,它们之间有一个下划线。 我想将它们分开并在变量中包含左侧部分(名称)和右侧部分(姓氏)。
基本上我想要相反的: String temp=name+"_"+surname;
使用split();
String[] parts = temp.split("_");
String name = parts[0];
String surname = parts[1]; // <-- comment
如果您的名称不包含下划线,注释行将抛出ArrayIndexOutOfBoundsException
。
您应该使用拆分。
String fullName = "name_surname";
String[] components = fullName.split("_");
String firstName = components[0];
String lastName = components[1];
只需使用 StringTokenizer
StringTokenizer st = new StringTokenizer(str, "_");
while (st.hasMoreElements()) {
System.out.println(st.nextElement());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.