我的数据是这样的:
Smith, Bob; Data; More Data
Doe, John; Data; More Data
如果你看下面你会看到我正在尝试将FullName分成第一个和最后一个。 错误是:
“String类型中的方法split(String)不适用于参数(char)”
String line = scanner.nextLine();
String[] data = line.split(";");
String[] fullName = data[0].split(',');
答案 0 :(得分:7)
我在my comment中解释过,错误很容易修复:','
→","
。
我将简要介绍一下为何会出现这种情况。在Java中,'
中包含的单个字符为character literals,与string literals中的split()
非常不同。例如,如果您来自Python世界,这可能需要一些时间才能习惯,因为"
和'
可以基本上同义使用。
在任何情况下,"
的单参数{{3}}方法只接受 一个String
,而String
又被解析为正则表达式。这就是你需要双引号的原因。
答案 1 :(得分:1)
将单引号切换为双引号
String[] fullName = data[0].split(",")
;
答案 2 :(得分:0)
String.split(String)将String作为唯一参数。
public String[] split(String regex)
Splits this string around matches of the given regular expression.
This method works as if by invoking the two-argument split method with the
given expression and a limit argument of zero. Trailing empty strings are
therefore not included in the resulting array.
The string "boo:and:foo", for example, yields the following results with
these expressions:
Regex Result
: { "boo", "and", "foo" }
o { "b", "", ":and:f" }
Parameters:
regex - the delimiting regular expression
Returns:
the array of strings computed by splitting this string around matches
of the given regular expression
Throws:
PatternSyntaxException - if the regular expression's syntax is invalid
Since:
1.4
See Also:
Pattern