
[英]Getting an array of all 1 character long substrings of a given String using split
[英]Split long string at given int [duplicate]
我有一个编程面试,他们让我写一个方法,将一个长字符串和一个 int 作为参数,并且该方法应该在数字的每个间隔处拆分字符串。 我无法理解如何做到这一点,所以我想我会在这里问,看看是否有人有任何想法。
顺便说一句:不幸的是我没有得到这份工作......
很遗憾听到采访的消息。 它糟透了......它发生了。 +1 用于跟进问题。
在拆分器函数中,我使用索引遍历“长字符串”。 每次迭代我都使用 String.substring 方法从字符串中提取间隔的大小。 (索引 + 间隔)。 提取后,我用间隔增加索引。 因此,通过长字符串,间隔一个间隔地移动。
可能会发生索引 + 间隔大于长字符串的长度。 (会导致越界异常)因此额外的检查来避免它,并保存剩余的字符串。
public static void main(String[] args) {
String veryLongString = "12345678901234567890";
List<String> subStrings = splitter(veryLongString, 3);
// Print the result
for (String s : subStrings) {
System.out.print(s + " ");
}
}
public static List<String> splitter(String string, int interval) {
int index = 0;
List<String> subStrings = new ArrayList<String>();
while (index < string.length()) {
// Check if there is still enough characters to read.
// If that is the case, remove it from the string.
if (index + interval < string.length()) {
subStrings.add(string.substring(index, index + interval));
} else {
// Else, less the "interval" amount of characters left,
// Read the remaining characters.
subStrings.add(string.substring(index, string.length()));
}
index += interval;
}
return subStrings;
}
输出:
123 456 789 012 345 678 90
对这次不幸感到抱歉。 下次好运。 我想用递归来回答这个问题。 它使算法更简单。
这是我遵循的原则
这是代码:
import java.util.ArrayList;
import java.util.List;
public class StringHelper {
private static List<String> workList = new ArrayList<String>();
private StringHelper()
{
}
public static void intervallSplit(String datas, int interval) {
if (datas.length() <= interval) {
workList.add(datas);
return;
}
workList.add( datas.substring(0,interval));
intervallSplit(datas.substring(interval), interval);
}
public static void main(String[] args) {
String text = "1234567891011121314151617181920";
intervallSplit(text, 3);
System.out.println(workList);
}
}
这是示例数据示例的输出
[123, 456, 789, 101, 112, 131, 415, 161, 718, 192, 0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.