如何拆分一串单词并保留空格?
这是代码:
String words[] = s.split(" ");
字符串 s 包含:hello world
代码运行后,words[]包含:"hello"
""
world
理想情况下,它不应该是中间的空字符串,而是包含两个空格:words[] 应该是:"hello"
" "
" "
world
我怎样才能得到这个结果?
你可以使用前瞻/后瞻 http://www.regular-expressions.info/lookaround.html断言:
String[] words = "hello world".split("((?<=\\s+)|(?=\\s+))");
where (?<=\\s+)
and (?=\\s+)
是零宽度组。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)