第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

如何在java中的文件中找到一個(gè)字符串并在它旁邊獲取字符串?

如何在java中的文件中找到一個(gè)字符串并在它旁邊獲取字符串?

慕的地6264312 2021-12-01 19:59:24
假設(shè)我有一個(gè)這樣的文件:Name: someone1 surnameAge: someNumber1Height: whoCares1Weight: someWeight1Name: someone2Age: someNumber2Height: whoCares2Weight: someWeight2Name: someone3Age: someNumber3Height: whoCares3Weight: someWeight3我想在ArrayList<String>.我只想為此使用Scanner類(lèi)。我嘗試使用如下代碼從文件中獲取“名稱(chēng):”部分:while(scanner.hasNextLine()) {            //read line by line            String line = scanner.nextLine();            //code to search for a word in the file which                 if(line.indexOf("Name:")!=-1) {                    // will search line by line for this word ignoring numbers in addition                    // I find the word with this, what next?                // I want to get word next to Name: and not only from one but from all the instances of the word Name:                }                else                    System.out.println("does not");        }我想在“名稱(chēng):”旁邊得到一個(gè)詞,不僅來(lái)自一個(gè)詞,而且來(lái)自“名稱(chēng):”這個(gè)詞的所有實(shí)例。我怎樣才能做到這一點(diǎn)?編輯:另外,如何在文件中分隔字符串,例如,如果我想將第一人稱(chēng)的姓名存儲(chǔ)在文件中,如someone1一個(gè) ArrayList 和surname另一個(gè) ArrayList 中。我如何將它們分開(kāi),并將它們存儲(chǔ)在新的 ArrayLists 中。
查看完整描述

2 回答

?
www說(shuō)

TA貢獻(xiàn)1775條經(jīng)驗(yàn) 獲得超8個(gè)贊

您可以嘗試使用String#matches來(lái)識(shí)別感興趣的線:


List<String> names = new ArrayList<>();


while (scanner.hasNextLine()) {

    String line = scanner.nextLine();

    if (line.matches("^Name:.*")) {

        names.add(line.replaceAll("^Name:\\s+", ""));

    }

}

這里的想法是獲取所有以 開(kāi)頭的行Name:,然后刪除Name:前綴,留下您想要的內(nèi)容。


使用的正則表達(dá)式說(shuō)明:


^      from start of string (line)

Name:  match text 'Name:'

\\s+   followed by any number of spaces (or other whitespace)

因此,通過(guò)刪除^Name:\\s+,我們應(yīng)該只剩下它左側(cè)的名稱(chēng)信息。


編輯:


例如,如果您的姓名內(nèi)容實(shí)際上是名字和姓氏,那么每一行將如下所示:


Name: George Washington

在這種情況下,如果格式固定,我們可以嘗試使用String#split隔離名和姓:


String[] parts = line.split("\\s+");

String first = parts[1];

String last = parts[2];

// then store first and last in separate lists

你會(huì)做什么完全取決于你的實(shí)際數(shù)據(jù)。這里有很多邊緣情況。也許有些行只有一個(gè)名字,或者有些行有中間名、首字母、后綴等。這只是為了給你一個(gè)大概的概念。


查看完整回答
反對(duì) 回復(fù) 2021-12-01
?
繁華開(kāi)滿(mǎn)天機(jī)

TA貢獻(xiàn)1816條經(jīng)驗(yàn) 獲得超4個(gè)贊

以下是從提供的文件中提取名稱(chēng)列表的功能方法:

public List<String> getNames(File file) throws IOException {    
                   return Files.lines(file.toPath())
            .filter(str -> str.contains("Name: "))
            .map(str -> str.split("Name: ")[1])
            .collect(Collectors.toList());}


查看完整回答
反對(duì) 回復(fù) 2021-12-01
  • 2 回答
  • 0 關(guān)注
  • 170 瀏覽
慕課專(zhuān)欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢(xún)優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)