我只想返回String
的第一个非重复字符,但它返回了我想要的答案和str
的值。如何使它只返回字符而不返回我的输入?
以下代码:
public class Main {
public static String getNumber(String str) {
for (char i : str.toCharArray()) {
if (str.indexOf(i) == str.lastIndexOf(i)) {
System.out.println("First non-repeating character is: " + i);
break;
}
}
return str;
}
public static void main (String[] args) {
Scanner s = new Scanner(System.in);
System.out.print(getNumber(s.nextLine()));
}
}
输入:
"abcdef"
输出:
First non-repeating character is: a
"abcdef"
通过使用String.valueOf
方法包装char变量修复:
for (char i : str.toCharArray()) {
if (str.indexOf(i) == str.lastIndexOf(i)) {
str = String.valueOf(i);
break;
}
}
return str;