因此,目标是在字符串中查找“zip”和“zap”等模式,以“z”开头并以“p”结尾。然后,对于所有此类字符串,删除中间的字母。
我的想法是,我使用 for 循环来检查字符串的每个字母,一旦到达“z”,它就会获取 indexOf('p') 并将其和中间的所有内容放入ArrayList,同时从原始字符串中删除自身,以便可以找到indexOf('p')。
我怎样才能做到这一点?
这是我到目前为止的代码:
package Homework;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.List;
public class ZipZap {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
List < String > list = new ArrayList < String > ();
System.out.print("Write a sentence with no spaces:");
String sen = in .next();
int len = sen.length();
int p1 = sen.indexOf('p');
String word = null;
String idk = null;
for (int i = 0; i < len; i++) {
if (sen.charAt(i) == 'z') {
word = sen.substring(i, p1 + 1);
list.add(word);
idk = sen.replace(word, "");
i = 0;
}
}
}
}
最佳答案
使用这个,这里我使用“\bz.p\b”模式来查找包含以z开头的字符并以p结尾的任何单词,之间可以有任何内容
String s ="Write a sentence with no zip and zap spaces:";
s=s.replaceAll("\\bz.p\\b", "zp");
System.out.println(s);
输出:
Write a sentence with no zp and zp spaces:
或者也可以
s.replaceAll("z\\w+p", "zp");
在这里你可以检查你的字符串
关于java - 如何将字符串的多个部分放入列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42172610/