在跳过空格时覆盖 Java 中的字符串

Overlay Strings In Java While Skipping Spaces

我想在 Java 中将两个字符串叠加在一起以形成一个字符串。我已经有一种方法可以做这样的事情,但不完全是我想要的。

例如,如果我告诉它用 " Hi" 覆盖 "Hello World",我将得到 " Hiorld"

我希望能够用 " Hi" 覆盖 "Hello World",并得到 "HelloHiorld"

这是我目前使用的方法:

public static String overlayString(String str, String overlay, int start, int end) {
          if (str == null) {
              return null;
          }
          if (overlay == null) {
              overlay = "";
          }
          int len = str.length();
          if (start < 0) {
              start = 0;
          }
          if (start > len) {
              start = len;
          }
          if (end < 0) {
              end = 0;
          }
          if (end > len) {
              end = len;
          }
          if (start > end) {
              int temp = start;
              start = end;
              end = temp;
          }
          return new StringBuffer(len + start - end + overlay.length() + 1)
              .append(str.substring(0, start))
              .append(overlay)
              .append(str.substring(end))
              .toString();
      }

如果我希望该方法避免用空格替换字符,但仍保持文本的定位,该方法会是什么样子?

你可以把第一个 String 放到一个 StringBuffer 中,使用循环检查第二个 String 中的哪些字符不是空格,然后使用 StringBuffer 的 .replace() 方法来替换这些字符。

例如,

StringBuffer sb = new StringBuffer("Hello World");
sb.replace(5, 7, "Hi");

给出 "HelloHiorld"

我可以通过两种方式实现这样的目标...

首先...

public static String overlay1(String value, String with) {
    String result = null;
    if (value.length() != with.length()) {
        throw new IllegalArgumentException("The two String's must be the same length");
    } else {
        StringBuilder sb = new StringBuilder(value);
        for (int index = 0; index < value.length(); index++) {
            char c = with.charAt(index);
            if (!Character.isWhitespace(c)) {
                sb.setCharAt(index, c);
            }
        }
        result = sb.toString();
    }
    return result;
}

这允许您传递相同长度的 Strings 并将替换第一个中第二个的所有 "non-whitespace" 内容,例如...

overlay1("Hello World", 
         "      Hi   "));

或者您可以指定要覆盖 String 的位置,例如...

public static String overlay2(String value, String with, int at) {
    String result = null;
    if (at >= value.length()) {
        throw new IllegalArgumentException("Insert point is beyond length of original String");
    } else {
        StringBuilder sb = new StringBuilder(value);
        // Assuming a straight replacement with out needing to 
        // check for white spaces...otherwise you can use
        // the same type of loop from the first example
        sb.replace(at, with.length(), with);
        result = sb.toString();
    }
    return result;
}

overlay2("Hello World", 
         "Hi", 
         5));