overlay a string with mask String - Java java.lang

Java examples for java.lang:String Format

Description

overlay a string with mask String

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String str = "java2s.com";
        String overlay = "!";
        int start = 2;
        int end = 4;
        System.out.println(overlay(str, overlay, start, end));
    }/* w  ww.j  av a  2 s  . c  o m*/

    public static final String EMPTY_STRING = "";

    public static String overlay(String str, String overlay, int start,
            int end) {
        if (str == null) {
            return null;
        }

        if (overlay == null) {
            overlay = EMPTY_STRING;
        }

        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();
    }

    
}

Related Tutorials