Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

Replace every nth character with "-" in java without regex

I am trying to replace every nth character in a string with some special character for e.g "-" so based on value of input (int n and String str), I want to replace all chars at n ( like 2, 4, 6) by this special characters so the length of string is maintained and this is what I have so far but it is not yielding correct output.

public String everyNth(String str, int n) {
      String result="";
      for(int i=0; i<str.length(); i+=n){
            result += " " + str.charAt(i);  
      } 
      return result;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What you could do is use a StringBuilder that will be initialized with your input String, then use setCharAt(int index, char ch) to modify a given char, this way you avoid building a new String at each iteration as you currently do with the operator += on String.

Something like:

public String everyNth(String str, int n) {
    if (n < 1) {
        throw new IllegalArgumentException("n must be greater than 0");
    }
    StringBuilder result = new StringBuilder(str);
    // This will replace every nth character with '-'
    for (int i = n - 1; i < str.length(); i += n) {
        result.setCharAt(i, '-');
    }
    return result.toString();
}

NB: Starts from n - 1 unless you want to replace the first character too if so starts from 0.


If you want to simply remove the characters, you should use the method append(CharSequence s, int start, int end) to build the content of your target String, as next:

public String everyNth(String str, int n) {
    if (n < 1) {
        throw new IllegalArgumentException("n must be greater than 0");
    }
    StringBuilder result = new StringBuilder();
    // The index of the previous match
    int previous = 0;
    for (int i = n-1; i < str.length(); i += n) {
        // Add substring from previous match to the current
        result.append(str, previous, i);
        // Set the new value of previous
        previous = i + 1;
    }
    // Add the remaining sub string
    result.append(str, previous, str.length());
    return result.toString();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...