首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将句子中的单个单词大写

将句子中的单个单词大写
EN

Stack Overflow用户
提问于 2013-01-07 09:21:31
回答 4查看 128关注 0票数 1

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

代码语言:javascript
运行
复制
    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);,但这将使其中包含搜索单词的所有行都大写,我想要做的就是突出显示搜索单词

EN

回答 4

Stack Overflow用户

发布于 2013-01-07 09:26:46

更改for循环,如下所示

代码语言:javascript
运行
复制
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));
   }
}

既然您知道需要大写的单词,为什么还要从文件中获取字符串并将其大写。

票数 0
EN

Stack Overflow用户

发布于 2013-01-07 09:28:02

下面是一个在字符串中大写单词的方法:

代码语言:javascript
运行
复制
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());
}

在这里使用它:

代码语言:javascript
运行
复制
System.out.println(capWord(Alice.get(i), word));
票数 0
EN

Stack Overflow用户

发布于 2013-01-07 09:51:41

尝尝这个

代码语言:javascript
运行
复制
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));
        }
    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14188656

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档