gpt4 book ai didi

字符串中的Java格式字

转载 作者:行者123 更新时间:2023-11-29 05:49:56 27 4
gpt4 key购买 nike

例如,我有一个包含一本书每一行内容的文本文件,我有一个 java 程序来搜索书中那些行中的特定单词。

这是程序:

import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;


public class AliceSearch {


public static void main(String[] args) throws Exception {

ArrayList<String> aiw = new ArrayList<String>();
ArrayList<String> matches = new ArrayList<String>();
Scanner scan = new Scanner(new File("aiw.txt"));
Scanner input = new Scanner(System.in);

while (scan.hasNext()){
aiw.add(scan.nextLine());
}

String searchTerm;

System.out.print("Please Input Search Parameter : ");

searchTerm = input.nextLine();

boolean itemFound = false;

String currItem = null;

for(int i = 0; i<aiw.size(); i++ ) {
currItem = (String)aiw.get(i);

if (currItem.contains(searchTerm)) {

matches.add(currItem);

itemFound = true;

}
}

System.out.println("");

if ( itemFound == false ) {

System.out.println ( "No results containing "+searchTerm );

}else{

System.out.println ( "We Found the following results : " );

for(int r = 0; r < matches.size(); r++){
System.out.println("");
System.out.println(matches.get(r));
}
}

scan.close();
input.close();

}

}

我希望每个结果行中的 searchTerm 在输出时(或放在匹配的 ArrayList 中时)都是大写的。我该怎么做?我知道您使用 .toUpperCase(); 但我现在不知道如何更改一串单词中的一个单词。

提前致谢!

最佳答案

而不是像现在这样输出它:

System.out.println(matches.get(r));

你不能用吗

System.out.println(matches.get(r).replace(searchTerm, searchTerm.toUpperCase()));

这是 JavaDoc replace() 方法用于将找到的单词替换为其大写版本。最好有

String uppercase = searchTerm.toUpperCase();

在循环外再使用

System.out.println(matches.get(r).replace(searchTerm, uppercase));

关于字符串中的Java格式字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14319896/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com