2016-04-23 24 views
-5
提取字

嗨,我有以下字符串:如何从一个字符串在Java中

NAME   Problem MAXIMIZE 

这是我通过逐行读取线文件的一部分。 我想提取字

问题

没有widespaces删除其他词

名称,最大限度地

,并保存结果变成一个变量。

下面是代码:

public void read(String datName) throws IOException { 
    String data = ""; 

    try { 
     BufferedReader br = new BufferedReader(new FileReader(datName)); 
     String zeile = ""; 

     try { 
      while ((zeile = br.readLine()) != null) { 
       data = data + zeile + "\r\n"; 
       lines.add(zeile); 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     try { 
      br.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } catch (FileNotFoundException e) { 

     e.printStackTrace(); 
    } 
    System.out.println(data); 
    this.data = data; 
} 

public void split() { 

    for (int i = 0; i < lines.size(); i++) { 
     if (lines.get(i).contains("NAME")) { 
      headerName = lines.get(i). 
    // If the String contains "NAME" it should give me the NAME which is "Problem" in my example 

     } 
    } 

我逐行读取文件中的行并将其保存在一个ArrayList。我只想要重要的信息。 我不期望一个算法,只是给我一些“单词”,我可以查找这个问题。

+0

尝试思考一些解决方案并提出它! – granmirupa

+0

你想要这个还是它是一个更大的问题的一部分,这只是一个例子!?你之前曾尝试过什么。请注意代码 –

+1

你有什么尝试?你的具体问题是什么?不要指望我们只给你代码/算法。 – bcsb1001

回答

1

您可以根据空格拆分字符串。

String myStr; //set this variable to your string 
String[] splitOnWhiteSpace = myStr.split(" "); 

然后你可以遍历数组中的每个元素:

String toFind; //set this with what you want to find 
for (String word : splitOnWhiteSpace) { 
if (word.equals(toFind)) { 
    //the word matches - do something with it 
} 
} 
0

您还可以使用的StringTokenizer:

StringTokenizer st = new StringTokenizer(line); 
while (st.hasMoreTokens()){ 
     If(st.nextToken().equals("Problem").......AND so 
} 
1

你可以使用这样的事情:

String[] strs = in.split(" "); 
in = strs[1]; 

当心!我没有试过这个。

相关问题