【问题标题】:Pulling headings from a String - Java从字符串中提取标题 - Java
【发布时间】:2012-07-11 14:22:38
【问题描述】:

只是想知道,从字符串的标题中提取信息的最佳方法是什么。

我有一个用于标题的类和 getter 方法(摘要、标题 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));
            }
        }
    } 

然而,这会抛出一个 Array Out of bounds 异常。

【问题讨论】:

  • 摘要和标题是多行段落吗?第一行怎么样?我们是否完全放弃第一行?
  • 听起来像家庭作业...?
  • 不是作业,我是实习生。第一个包含文本的框是 one String

标签: java string parsing


【解决方案1】:

使用 Scanner 对象。

import java.util.Scanner;

然后使用它一次读取一行字符串。

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

现在 sc.hasNext() 会告诉您是否还有要读取的行,并且 sc.next() 返回下一行。使用它一次遍历字符串一行。您可以测试每一行以查看它是否等于“Summary:”或“Heading 1:”等。然后您可以使用 StringBuffer 从您要创建的每个字符串中添加每一行。

如果你愿意,我可以为你写这个,但它相当简单。

【讨论】:

  • 感谢您的回答!我现在就试试。
  • 我现在只是在尝试,如果说“摘要”包含多行信息,我该怎么办?比如我怎么知道什么时候停止阅读特定标题的行?
  • 我会继续将每一行追加到 StringBuffer 中,直到您到达显示它一定已经结束的行。如果您的格式始终为“摘要:somelines 标题 1:somelines”,那么您可以继续直到找到等于“标题 1:”的行。
  • 不幸的是,这种格式并不总是如此,有些标题可能不存在..有什么建议吗?
  • 您只需要找到所有文档共有的某种标志,用于分隔不同的部分并寻找它。也许总是有一个空白行分隔部分。也许行只在一个部分的开头以冒号结尾。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-15
  • 1970-01-01
  • 1970-01-01
  • 2012-01-23
  • 1970-01-01
  • 2018-10-25
相关资源
最近更新 更多