有没有办法取以下句子:
“我想把它分成几对”
并使用 java 生成以下列表:
“我想要”、“想要这个”、“这个分裂”、“分裂”、“成对”、“成对”
有一种方法,其中一种方法可以是很多方法:
String string = "I want this split up into pairs";
String[] words = string.split(" ");
List<String> pairs = new ArrayList<String>();
for (int i = 0; i < words.length-1; ++i) {
pairs.add(words[i] + " " + words[i+1]);
}
System.out.println(pairs);
这是一个基本算法
标记或拆分您的句子
I want this split up into pairs -> I, want, this, split, up, into, pairs
然后
first = read first word
while(there are more words to read){
second = read next word
Print first + " " + second
first = second
}
一个例子如下:
String text = "I want this split up into pairs";
String[] words = text.split(" ");
//Print 2 combined words
for(int i=1;i<words.length;i++)
{
System.out.printf("%s %s\n", words[i-1],words[i]);
}
控制台中的输出:
I want
want this
this split
split up
up into
into pairs
不是一个巨大的 java 人,所以不确定这段代码是否 100%,但这是一个选项的一般想法。
String x = "I want this split up into pairs";
String[] parts = x.split(" ");
List<String> newParts = new ArrayList<String>();;
for (int i = 0; i < parts.length()-1; i++) {
newParts.add(parts[i]+parts[i+1]);
}
然后,newParts List 将包含您所有的配对