有没有办法从java
中的字符串中拆分单词?
String my ="StackOverFlow PF Apple FT Laptop HW."
PF =平台,FT =水果,HW =硬件。
预期输出应为
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));
}
答案 0 :(得分: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个为一组。这意味着您可以检查单词的索引是偶数还是奇数。如果它是偶数,那么你知道它是第一个配对词,这意味着你可以将“is a”字符串附加到它上面。如果它是奇数,那么你想附加翻译的值。
答案 1 :(得分: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");
}
答案 2 :(得分: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.
答案 3 :(得分: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;
}
}