如何在Java/Android中删除字符串首个空格后的字符,仅保留空格前内容
实现方法
方法1:使用split()方法分割字符串
按空格切割字符串,取切割后的第一个数组元素即可,代码示例:
String name = "Jhon Doe"; // 按空格分割,limit设为2避免多余切割,提升效率 String[] nameParts = name.split(" ", 2); String firstName = nameParts[0]; textView.setText("Hi " + firstName);
注意:如果原字符串不存在空格,split返回的数组长度为1,直接取第一个元素也能正常拿到完整字符串,不会报错
方法2:使用indexOf() + substring() 截取(性能更优)
先找到第一个空格的索引位置,直接从开头截取到空格位置即可,不需要生成额外数组:
String name = "Jhon Doe"; String firstName; int spaceIndex = name.indexOf(' '); if (spaceIndex != -1) { // 存在空格,截取到空格前的位置 firstName = name.substring(0, spaceIndex); } else { // 不存在空格,直接用原字符串 firstName = name; } textView.setText("Hi " + firstName);
这种方式比split性能更好,尤其是处理大量字符串的时候优势更明显。
内容的提问来源于stack exchange,提问作者Vishal Beep
相关产品推荐
相关产品推荐

