假设我的分隔符是 ','(逗号),我正在寻找一个函数 split
来保证返回的 String[] 数组具有一定的大小(不多也不少) :
String[] split(String str, int limit);
split("hello", 2); => ["hello", ""]
split("hello,", 2); => ["hello", ""]
split(",hello", 2); => ["", "hello"]
split("hello,world", 2); => ["hello", "world"]
split("hello,world,goodbye", 2); => ["hello", "world,goodbye"]
看到数组大小如何始终为 2 了吗?我可以通过 Pattern.split 获得一些这种行为,但并非适用于所有情况……我该怎么做?
最佳答案
您可以使用 Arrays.copyOf()
返回一个填充数组。但是,填充将为 null
而不是空字符串。
String[] parts = Arrays.copyOf("hello,".split(",", 2), 2);
String[] parts1 = Arrays.copyOf(",hello".split(",", 2), 2);
String[] parts2 = Arrays.copyOf("hello,world".split(",", 2), 2);
String[] parts3 = Arrays.copyOf("hello,world,goodbye".split(",", 2), 2);
String[] parts4 = Arrays.copyOf("hello,".split(",", 2), 4); //null padding
关于java - 将字符串拆分为特定大小的 String[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4444341/