将目标对象中的空串替换成对应的字符

import org.apache.commons.lang.StringUtils;

public class ReplaceTest {


    public static void main(String[] args) {


        //情况1:target的长度=source的长度
        String source1 = "HelloWorld";

        String target1 = "hello orld";

        System.out.println("source1:" + source1 + "    " + "target1:" + target1);

        System.out.println("情况1:target的长度=source的长度,结果为:" + contrastString(source1, target1));

        //情况2:target的长度source的长度
        String source3 = "HelloWorld";

        String target3 = "helloWorld friends";

        System.out.println("source3:" + source3 + "    " + "target3:" + target3);

        System.out.println("情况3:target的长度>source的长度,结果为:" + contrastString(source3, target3));
    }


    /**
     * target目标对象中的空串替换成source对应位置的字符
     *
     * @param source
     * @param target
     * @return
     */
    public static String contrastString(String source, String target) {

        if (StringUtils.isEmpty(target) || StringUtils.isEmpty(source)) {
            return "";
        }
        int targetLength = target.length();
        int sourceLength = source.length();

        int length = targetLength <= sourceLength ? targetLength : sourceLength;

        StringBuilder sb = new StringBuilder(target);

        for (int i = 0; i < length; i++) {
            if (Character.isWhitespace(target.charAt(i))) {
                sb.replace(i, i + 1, String.valueOf(source.charAt(i)));
            }
        }

        if (sourceLength > targetLength) {
            sb.append(source, length, sourceLength);
        }

        return sb.toString();


    }
}

输出如下图所示:

将目标对象中的空串替换成对应的字符_第1张图片

 

你可能感兴趣的:(Java,replace,java)