I want add a random letter after each N-th letter. Which is the best way to achieve this?
Example: I have string like this: aaaaaaaaaaaaaaaaa, and i want to get this: aaamaaaeaaa4aaamaaalaa
CodePudding user response:
You can try the below code:
public class Test {
public static void main(String[] args) {
String originalString = "aaaaaaaaaaaaaaaaa";
int skipcharactorCount = 3;
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(originalString.charAt(0));
for (int i = 1; i < originalString.length(); i ) {
if (i%skipcharactorCount==0){
stringBuilder.append(getRandomChar());
}
stringBuilder.append(originalString.charAt(i));
}
System.out.println(stringBuilder.toString());
}
private static char getRandomChar() {
return (char) ((int) (Math.random() * 1000) % 26 97);
}
}
Here I am converting a random number to a lowercase character
CodePudding user response:
This would be one solution:
public String addRandomLetter(int chunkSize, String str)
{
String[] arr = str.split("(?<=\\G.{" chunkSize "})"); // Split the string into chunks of size chunkSize
Random r = new Random();
// Add for each chunk a random character at the end
for (int i = 0; i < arr.length; i )
{
char c = (char)(r.nextInt(26) 'a');
arr[i] = c;
}
return String.join("", arr); // Join the chunks into one big string.
}
CodePudding user response:
There are heaps of ways you could do this. You could make a Python script. Use a for loop:
import random
import string
for x in range(totalLetters):
if(x % n == 0):
print(random.choice(string.ascii_letters))
else:
print("some letter")
The so the for loop basically counts from 1 to totalLetters. Then the if statement checks if n letters has passed. It's just a base and you can go from there.