I need to insert a Character such as a at multiples of a var
I need to insert a Character, such as a, at multiples of a variable into a java, string literal. For example, if the string litreal is: Hello world and the variable z is 2. The program will need to insert \'a\' into the string literal at multiples of 2. So at positions 2,4,6,8,10 and so on until the end of the literal.
The new literal should = Heallao waoralda.
Solution
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class insertCharacter {
public static String manipulate(String t,int c)
{
String ret=\"\";
int j=c;
for(int i=0;i<t.length();i++)
{
j=i+c;
if(j<t.length())
ret=ret+t.substring(i, j)+\"a\";
i=i+(c-1);
}
return ret;
}
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println(\"Enter the string literal: \");
String str = br.readLine();
System.out.println(\"Enter the variable: \");
int a = Integer.parseInt(br.readLine());
System.out.println(\"The new literal = \"+manipulate(str,a));
}
}
