replace a string case insensitive - Java java.lang

Java examples for java.lang:String Replace

Introduction

The following code shows how to replace a string case insensitive.

Demo Code

//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String target = "java2s.com";
        String sub = "O";
        String rep = "O";
        boolean nocase = true;
        System.out.println(replace(target, sub, rep, nocase));
    }// w  w  w  . j  a  v a 2 s . c  o  m

    public static String replace(String target, String sub, String rep,
            boolean nocase) {
        int i, prev = 0, j = sub.length();
        if (nocase) {
            target = target.toLowerCase();
            sub = sub.toLowerCase();
        }
        ;
        for (;;) {
            i = target.indexOf(sub, prev);
            if (i < 0)
                break;
            target = target.substring(0, i) + rep + target.substring(i + j);
            prev = i + rep.length();
        }
        ;
        return target;
    }
}

Related Tutorials