2016-08-24 70 views
0

有沒有什麼辦法可以從java?中的一個字符串中分離單詞。從java中的一個字符串中分出特定單詞

String my ="StackOverFlow PF Apple FT Laptop HW." 

PF = Platform,FT = Fruit,HW = Hardware。

預期的輸出應該

StackOverFlow is a Platform. 
Apple is a Fruit. 
Laptop is a hardware. 

我做了這種方式:

String[] words = my.split(" "); 
    for(int u=0 ; u<words.length ; u++){ 
     System.out.println(words(u)); 
    } 
+1

是。你編寫代碼來分割字符串。然後你檢查匹配結果,並相應地改變這些詞。 – durbnpoisn

+0

@durbnpoisn我應該先刪除所有空格嗎? – user6750923

+2

你可以像'String [] words = my.split(「」);'這樣創建一個數組,其中包含沒有空格的每個單詞,按照傳入的令牌。 – Orin

回答

0
public class StackOverflow { 

    public static void main(String[] args) { 
     // Fields 
     String myString = "StackOverFlow PF Apple FT Laptop HW"; 

     String[] tokens = myString.split(" "); 

     for (int i = 0; i < tokens.length; i++) { 
      System.out.print(tokens[i]); 
      // Every other token 
      if (i % 2 == 0) { 
       System.out.print(" is a " + convert(tokens[i + 1])); 
       i++; 
      } 
      System.out.println(); 
     } 

    } 

    /** 
    * convert method turns the abbreviations into long form 
    */ 
    private static String convert(String s) { 
     String str; 
     switch (s) { 
      case "PF": 
       str = "Platform"; 
       break; 
      case "FT": 
       str = "Fruit"; 
       break; 
      case "HW": 
       str = "Hardware"; 
       break; 
      default: 
       str = "Unknown"; 
       break; 
     } 
     return str; 
    } 

} 
0

如果你能保證值將按照上述順序,這樣的事情應該工作

public static void main(String[] args) { 
    String my = "StackOverflow PF Apple FT Laptop HW"; 
    String[] words = my.split(" "); 
    for (i = 0; i < words.length; i++) { 
     if (i % 2 == 0) { 
      System.out.print(words(i) + " is a "); 
     } else { 
      System.out.println(getTranslation(words(i))); 
     } 
    } 
} 

private String getTranslation(String code) { 
    if ("PF".equals(code)) { 
     return "Platform"; 
    } 
    //etc... 
} 

本質上,這將做的是將字符串拆分爲所有的單詞。由於這些單詞是「配對」在一起的,因此它們會以2個爲一組。這意味着您可以檢查該單詞的索引是偶數還是奇數。如果它是偶數,那麼你知道這是第一個配對詞,這意味着你可以附加「是」一個字符串。如果它很奇怪,那麼你想追加翻譯後的值。

0

使用正則表達式AMD在2個字組拆分孔文...

然後分裂空格數組的每一個元素,就大功告成了!

例子:

public static void main(String[] args) throws ParseException { 
String inputTxt = "StackOverFlow PF Apple FT Laptop HW."; 
String[] elements = inputTxt.split("(?<!\\G\\w+)\\s"); 
System.out.println(Arrays.toString(elements)); 
System.out.println(elements[0].split(" ")[0] + " is a Platform"); 
System.out.println(elements[1].split(" ")[0] + " is a Fruit"); 
System.out.println(elements[2].split(" ")[0] + " is a Hardware"); 
} 
0

鑑於你的問題的限制規範,沒有理由分裂。只需更換您的佔位符這樣的:

String my = "StackOverFlow PF Apple FT Laptop HW."; 
my = my.replaceAll("PF[\\s.]?", " is a Platform.\n"); 
my = my.replaceAll("FT[\\s.]?", " is a Fruit.\n"); 
my = my.replaceAll("HW[\\s.]?", " is a hardware.\n"); 
System.out.print(my); 

輸出:

StackOverFlow is a Platform. 
Apple is a Fruit. 
Laptop is a hardware. 
相關問題