为什么不能用美元符号分割字符串? [英] Why can't I split a string with the dollar sign?

查看:213
本文介绍了为什么不能用美元符号分割字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想分割一个具有如下内容的字符串:

I want to split a string which has content like this:

a$b$c

但是当我使用时:

String data=...
data.split("$");

它不能识别$并且不分割字符串,但是当我用$像X这样的字母替换$时,它可以工作. 有人有什么主意吗?

it does not recognize $ and do not split string but when I replace $ by some Letter like X it works. does anyone has any Idea?

推荐答案

split函数采用正则表达式(而不是字符串)进行匹配.您的正则表达式使用特殊字符-在本例中为'$'-因此您需要对其进行更改以转义该字符:

The split function takes a regular expression, not a string, to match. Your regular expression uses a special character - in this case '$' - so you would need to change it to escape that character:

String line = ...
String[] lineData = line.split("\\$");

还请注意,split返回一个字符串数组-字符串是不可变的,因此无法修改.对String所做的任何修改都将以新的String返回,并且原始值将不会更改.因此,上面的lineData = line.split("\\$");.

Also note that split returns an array of strings - Strings are immutable, so they cannot be modified. Any modifications made to the String will be returned in a new String, and the original will not be changed. Hence the lineData = line.split("\\$"); above.

这篇关于为什么不能用美元符号分割字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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