【发布时间】:2020-04-11 20:55:44
【问题描述】:
我想通过扫描仪读取一个字符的索引,然后将其从字符串中删除。只有一个问题:如果 char 在字符串中出现多次,.replace() 会删除所有字符。
例如,我想从字符串“Texty text”中获取第一个“t”的索引,然后只删除那个“t”。然后我想获取第二个't'的索引,然后将其删除。
import java.util.Scanner;
class Main {
public static void main(String[] args) {
String text = "Texty text";
Scanner sc = new Scanner(System.in);
int f = 0;
int x = 0;
while(f<1){
char c = sc.next().charAt(0);
for(int i = 0; i<text.length();i++){
if(text.charAt(i)==c){
System.out.println(x);
x++;
}
else{
x++;
}
}
}
System.out.println(text);
}
}
【问题讨论】:
-
" while(f
-
我不知道您的问题与您的代码有何关系。您想替换第一个
t,然后是第二个t,依此类推,目前(您声称)它替换了所有t(s)。 如何?您不要在此代码中使用replace。我跑了它。如果您删除无限的while循环并输入t,您会得到:3\n6\n9\nTexty 文本(其中\n是换行符)。你想要什么?
标签: java