从java中的一个字符串中分出特定单词

问题描述:

有没有什么办法可以从java?中的一个字符串中分离单词。从java中的一个字符串中分出特定单词

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

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

预期的输出应该

* 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

public class * { 

    public static void main(String[] args) { 
     // Fields 
     String myString = "* 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; 
    } 

} 

如果你能保证值将按照上述顺序,这样的事情应该工作

public static void main(String[] args) { 
    String my = "* 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个为一组。这意味着您可以检查该单词的索引是偶数还是奇数。如果它是偶数,那么你知道这是第一个配对词,这意味着你可以附加“是”一个字符串。如果它很奇怪,那么你想追加翻译后的值。

使用正则表达式AMD在2个字组拆分孔文...

然后分裂空格数组的每一个元素,就大功告成了!

例子:

public static void main(String[] args) throws ParseException { 
String inputTxt = "* 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"); 
} 

鉴于你的问题的限制规范,没有理由分裂。只需更换您的占位符这样的:

String my = "* 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); 

输出:

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