java - 将句子中的单个单词大写

标签 java

我需要它做的就是将每行搜索到的单词大写,所以我已经有了`

    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); 但这会将其中搜索到的单词的所有行大写,我想做的就是突出显示搜索词

最佳答案

这是一种将字符串中的单词大写的方法:

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));

关于java - 将句子中的单个单词大写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14188656/

相关文章:

java - 如何在 StackedBarChart 上设置交替条形的样式

java - 忽略带有lucene的特殊字符?

java - Swagger Spring API - xmlModelPlugin 错误

java - 为什么 value/100 返回 0?

java - GLThread java.lang.NullPointerException 错误

java - Struts 2.3错误: Unable to load configuration and similar errors

java - 使用类似于 Visual Studio C#/VB 的 Eclipse 创建 SWT 表单,可能吗?

java - Android [string array] 无法解析或不是字段

java - 什么是Java的-XX :+UseMembar parameter

java - 如何让管道命令也返回 Java exec 中的输出?