2016-04-23 23 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]; 

當心!我沒有試過這個。

相關問題