-4

Suppose the string is like this:

String msg = "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"

I want to add a character supposing 'f' after every 10 character iteration using subString function because I can't call StringBuilder class ( used it for insert or append functionality).

2 Answers2

0
public class HelloWorld{

 public static void main(String []args){
     int i = 10;

    String msg = "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"; 
       while(i <= msg.length())
        {
           msg = msg.substring(0, i) + "f" + msg.substring(i, msg.length());
           i = i + 11; 

        }
    System.out.println(msg);
 }
}
-1

It may help you

public static String insertPeriodically(String text, String insert, int period)
{
StringBuilder builder = new StringBuilder(text.length() + insert.length() * (text.length()/period)+1);

int index = 0;
String prefix = "";
while (index < text.length())
{
    // Don't put the insert in the very first iteration.
    // This is easier than appending it *after* each substring
    builder.append(prefix);
    prefix = insert;
    builder.append(text.substring(index, 
        Math.min(index + period, text.length())));
    index += period;
}
return builder.toString();
}
  • 1
    This answer is exact copy of @JonSkeet answer in the [Putting char into a java string for each N characters](http://stackoverflow.com/questions/537174/putting-char-into-a-java-string-for-each-n-characters). – Ravikumar Sep 22 '16 at 13:20