【发布时间】:2019-10-21 03:03:02
【问题描述】:
我正在编写一个程序,它应该在单词中忽略 ( 和 )(不使用 RegExp),并且通过我创建的方法,我希望我的变量 x 记住新的字符串。如何以这种方式访问 subSequence 或通过不包括使用 RegExp 的另一种方法来规避我的问题?
public int removeParentheses(char[] str) {
// To keep track of '(' and ')' characters count
int count = 0;
for (int i = 0; i < str.length; i++)
if (str[i] != '(' && str[i] != ')')
str[count++] = str[i];
return count;
}
public String foo(String input) {
for (String index : input.split(" ")) {
char[] charArray = index.toCharArray();
int k = removeParentheses(charArray);
String x = String.valueOf(charArray).subSequence(0, k); // that's what i want to do. it doesn't work.
System.out.println(String.valueOf(charArray).subSequence(0, k)); // this is the only way i can make it work, but it doesn't suffice my needs
}
}
当前输出为
error: incompatible types: CharSequence cannot be converted to String
String x = String.valueOf(charArray).subSequence(0, k);
^
1 error
我希望boo) 的输出在我的x 变量中是boo,而不仅仅是通过System.out.println 方法在屏幕上显示。
【问题讨论】:
-
您正在使用
CharSequence#subSequence,它返回一个CharSequence。改用String#substring,因为它返回String。
标签: java subsequence