簡體   English   中英

從字符串中提取標題-Java

[英]Pulling headings from a String - Java

只是想知道,從字符串標題中提取信息的最佳方法是什么。

我有一個用於標題的類和獲取方法(摘要,標題1,標題2)。

例如,

如果我的字串等於

This: is the first line of a String: xx-string: This is a long String

Summary:
This is the summary of the String

Heading 1:
This is the first heading

Heading 2:
This is another heading

設置字符串值的理想方法是,

摘要,標題1,標題2

Summary = This is the summary of the String
Heading 1 = This is the first heading
Heading 2 = This is another heading

謝謝 !!

編輯

這就是我要的

 public void setHeadings(Data fileData) {
        String description = fileData.getDescription();
        //String [] headings = description.split(":");

        int indexOf;
        indexOf = description.indexOf("Summary");
        if(indexOf != -1)
        {
            String subString = description.substring(indexOf);
            int indexOfNextHeading = subString.indexOf(":");
            if(indexOfNextHeading != -1)
            {
                System.out.println(indexOf + ":" + indexOfNextHeading);
                setSummary(description.substring(indexOf,indexOfNextHeading-1));
                System.out.println(description.substring(indexOf,indexOfNextHeading));
            }
        }
    } 

但是,這會拋出“數組越界”異常。

使用掃描儀對象。

import java.util.Scanner;

然后使用它一次讀取String。

Scanner sc = new Scanner(string);
sc.useDelimiter("\n");  // read one line at a time

現在sc.hasNext()告訴您是否還有剩余的行需要讀取,而sc.next()返回下一行。 使用此函數一次遍歷String一行。 您可以測試每一行以查看它是否等於“ Summary:”或“ Heading 1:”等。然后,您可以使用StringBuffer從要創建的每個String中添加每一行。

如果您願意,我可以為您編寫代碼,但這很簡單。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM