对,我需要它做的是将每行搜索到的单词大写,所以我已经有了`
File myFile = new File("AliceInWonderland.txt");
Scanner scan = new Scanner(myFile);
Scanner uInput = new Scanner(System.in);
String word;
int count = 0;
ArrayList<String> Alice = new ArrayList<String>();
System.out.println("Select the word that you would like to search for, from the book of alice and wonderland: ");
word = uInput.next();
while(scan.hasNext()){
Alice.add(scan.nextLine());
}
for(int i = 0;i <= Alice.size();i++){
if(Alice.get(i).contains(word)){
System.out.println(Alice.get(i));
count++;
}
else{
System.out.println(Alice.get(i));
}
}` 我可以编写System.out.println(Alice.get(i).ToUpper);,但这将使其中包含搜索单词的所有行都大写,我想要做的就是突出显示搜索单词
发布于 2013-01-07 09:26:46
更改for循环,如下所示
for(int i = 0;i <= Alice.size();i++)
{
if(Alice.get(i).contains(word))
{
System.out.println(word.toupperCase());
count++;
}
else
{
System.out.println(Alice.get(i));
}
}既然您知道需要大写的单词,为什么还要从文件中获取字符串并将其大写。
发布于 2013-01-07 09:28:02
下面是一个在字符串中大写单词的方法:
private static String capWord(String s, String w) {
int k = s.indexOf(w);
if (k < 0)
return s;
return s.substring(0, k) + w.toUpper() + s.substring(k + w.length());
}在这里使用它:
System.out.println(capWord(Alice.get(i), word));发布于 2013-01-07 09:51:41
尝尝这个
int wordLength = word.length();
for(int i = 0;i < Alice.size();i++){
if(Alice.get(i).contains(word)){
for(int c=0;c<Alice.get(i).length()-wordLength;c++){
if(Alice.get(i).substring(c, c+wordLength).equals(word)){
System.out.print(Alice.get(i).substring(0, c));
System.out.print(Alice.get(i).substring(c, c+wordLength).toUpperCase());
System.out.print(Alice.get(i).substring(c+wordLength, Alice.get(i).length()) + "\n");
}
}
count++;
}
else{
System.out.println(Alice.get(i));
}
}https://stackoverflow.com/questions/14188656
复制相似问题