gpt4 book ai didi

java - 在 Java 中生成字符串标记

转载 作者:行者123 更新时间:2023-11-29 10:04:13 26 4
gpt4 key购买 nike

我想在 Java 中使用前向遍历生成可能的标记。例如,如果我有一个字符串“这是我的车”。我需要生成 token

  • “这是我的车”
  • “这是我的”
  • “这是”
  • “这个”
  • “是我的车”
  • “是我的”
  • "is"
  • “我的车”
  • “我的”
  • “汽车”

最好的方法是什么?有什么例子吗?谢谢。

最佳答案

这是另一种使用拆分和嵌套循环的解决方案:

public static void main(String[] args) {
String original = "this is my car";

String[] singleWords = original.split(" "); // split the String to get the single words
ArrayList<String> results = new ArrayList<String>(); // a container for all the possible sentences
for (int startWord = 0; startWord < singleWords.length; startWord++) { // starWords start with 0 and increment just until they reach the last word
for (int lastWord = singleWords.length; lastWord > startWord; lastWord--) { // last words start at the end and decrement just until they reached the first word
String next = "";
for (int i = startWord; i != lastWord; i++) { // put all words in one String (starting with the startWord and ending with the lastWord)
next += singleWords[i] + " ";
}
results.add(next); // add the next result to your result list
}
}

// this is just to check the results. All your sentences are now stored in the ArrayList results
for (String string : results) {
System.out.println("" + string);
}
}

这是我测试该方法时的结果:

this is my car 
this is my
this is
this
is my car
is my
is
my car
my
car

关于java - 在 Java 中生成字符串标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13822270/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com