且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么不能用美元符号分割字符串?

更新时间:2022-05-14 08:16:34

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.