java split方法无法按预期工作 [英] java split method not working as expected

查看:85
本文介绍了java split方法无法按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在java中的split方法面临这个小问题。不确定这是一个已知的...请帮助。



Hi, I am facing this small issue on the split method in java. Not sure this is a known one or not.. please help.

String tmp = "Hello I      am fine   ";
String str[] = tmp.split(" ");
System.out.println("STR[0] => " + str[0]);
		
String tmp1 = "  Hello I      am fine   ";
String str1[] = tmp1.split(" ");
System.out.println("STR1[0] => " + str1[0]);





输出如下:





Output as below:

STR[0] => Hello
STR1[0] =>





As你可以看到,如果hello字之前有一个空格,就会发生这种情况..这有什么办法吗?我知道split将regex作为参数,但是如果它存在于单词之前,还是必须有一种跳过第一个空白空间的方法吗?对吗?



提前谢谢。



As you can see, if there is a space before "hello" word, this is happening.. is there is any workaround for this? I know that split takes regex as argument, but still there has to be a way to skip the first empty space if it exists before the word ? right?

Thanks in advance.

推荐答案

在分割之前尝试对字符串进行修剪。 Trmming将删除所有前导和尾随空格。

Try triming the string before splitting. Trmming will remove all the leading and trailing whitespaces.
String tmp = "Hello I      am fine   ";
String str[] = tmp.trim().split(" ");
System.out.println("STR[0] => " + str[0]);

String tmp1 = "  Hello I      am fine   ";
String str1[] = tmp1.trim().split(" ");
System.out.println("STR1[0] => " + str1[0]);


这篇关于java split方法无法按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆