【问题标题】:Split long string at given int [duplicate]在给定的 int 处拆分长字符串 [重复]
【发布时间】:2015-04-10 22:23:28
【问题描述】:

我有一次编程面试,他们要求我编写一个方法,该方法接受一个长字符串和一个 int 作为参数,并且该方法应该在数字的每个间隔处拆分字符串。我不明白如何做到这一点,所以我想我会在这里问一下,看看是否有人有任何想法。

顺便说一句:不幸的是我没有得到这份工作......

【问题讨论】:

  • 不要难过。尽可能阅读和使用 Java API。这将有助于解决这样的简单任务。
  • 感谢漂亮(但不是很好......)cmets。我知道这是我应该知道的,但我就是不知道。谁能写出解决方案?
  • 只需要一个 for 循环和 String substring 方法。
  • @jHilscher 感谢您指出 \\G 在 java 中的可用性。

标签: java string


【解决方案1】:

很遗憾听到采访的消息。这很糟糕......它发生了。 +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

【讨论】:

  • 非常感谢。现在看起来很明显,但我想我还有一些学习要做。我(当然)应该能够解决这个问题。再次感谢! :)
【解决方案2】:

很抱歉给您带来不幸。下次运气更好。我想用递归来回答这个问题。它使算法更简单。

这是我遵循的原则

  1. 如果字符串的长度小于或等于间隔,我们将其存储并退出该方法
  2. 否则,我们将子字符串从索引 0 变为区间 -1,即 String.subString(0, interval) 并存储,然后调用 String.subString(interval) 上的方法

代码如下:

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]

【讨论】:

    猜你喜欢
    • 2015-04-16
    • 2015-03-31
    • 2012-07-22
    • 1970-01-01
    • 1970-01-01
    • 2012-10-30
    • 2014-01-02
    • 2013-05-05
    相关资源
    最近更新 更多