2014-06-06 2 views
0

Мне нужен метод replace(), который мог бы заменить строку с иглой в строке стога сена, нечувствительным к регистру. Мне также нужно, чтобы это было сделано без какого-либо регулярного выражения. Я не мог найти такого метода, поэтому написал свой собственный. Этот вопрос заключается в том, чтобы документировать его, если кто-то еще найдет его полезным в будущем. И если любые улучшения могут быть сделаны (без использования String.replace), не стесняйтесь предлагать их.Нечувствительный к регистру метод replace() в Java (с использованием indexOf)

+0

возможно дубликат [Как заменить регистронезависимых буквенные подстроки в Java] (http://stackoverflow.com/questions/5054995/how-to-replace-case-insensitive-literal-substrings -in-java) – Braj

+0

Почему вы не хотите использовать метод 'replace()' и 'repalceAll()'? Есть ли какая-то конкретная причина? – Braj

+0

@Braj Мне нужно, чтобы замена была нечувствительной к регистру, а также я использую google web takeit, который компилирует java-код в javascript. Поэтому регулярные выражения и т. Д. Должны быть совместимы с javascript. Таким образом, нет простого способа избежать входа пользователя, поэтому его можно использовать вместо replaceAll. –

ответ

1
public static String replace(String needle, String hayStack, String replacement) 
{ 
    String origNeedle = needle; 
    String origHayStack = hayStack; 

    needle = origNeedle.toLowerCase(); 
    hayStack = origHayStack.toLowerCase(); 

    int hayStackLen = hayStack.length(); 
    int needleLen = needle.length(); 
    int from = 0; 
    int to; 

    String stuffBeforeNeedle; 
    StringBuilder output = new StringBuilder(); 

    do 
    { 
     to = hayStack.indexOf(needle, from); 
     if (to == -1) 
      to = hayStackLen; 

     stuffBeforeNeedle = hayStack.substring(from, to); 
     output.append(stuffBeforeNeedle); 

     if (to < hayStackLen) 
      output.append(replacement); 

     from = hayStack.indexOf(needle, to) + needleLen; 
    } 
    while (to < hayStackLen); 

    return output.toString(); 
} 
0
public static void main(String[] args) throws IOException, ApplicationException, InterruptedException 
{ 
    String output = ""; 

    String haystack = "This is the end. The beautiful EnD. No safety or surprise, the eND. La la la!"; 
    String needle = "eNd"; 

    String replacement = "beginning"; 

    String searchHaystack = haystack.toLowerCase(); 
    String searchNeedle = needle.toLowerCase(); 

    int substringStart = 0; 
    int beginningOfNeedle = -1; 
    while(true) 
    {   
     // Finds the first needle in the haystack, starting the search just after the last one we found. 
     // (On the first iteration, we start from the first character). 
     beginningOfNeedle = searchHaystack.indexOf(searchNeedle, ++beginningOfNeedle); 

     // If we can't find another needle, we're done. 
     if(beginningOfNeedle == -1) 
      break;   

     // If we found a needle, we add to our output the substring of haystack 
     // that starts from substringStart and goes right up to the beginning of the needle 
     // we just found. 
     output += haystack.substring(substringStart, beginningOfNeedle); 
     // We also add the replacement text. 
     output += replacement; 

     // The next substring will start right at the end of the needle. 
     substringStart = beginningOfNeedle + needle.length(); 
    } 
    // We add the last substring (which runs through the end of the haystack) 
    // to the output. 
    output += haystack.substring(substringStart); 


    System.out.println(output); 
} 
Смежные вопросы