重复字符串java中的特定字符

时间:2017-08-13 13:30:56

标签: java string character repeat

我有一个问题。我正在努力练习,我被要求从用户那里得到一个字符串,一个我要在这个字符串中复制的字符,以及一个数字 - 我要复制多少次。例如:字符串输入:dog;性格:o;数量:4。输出:doooog。我的问题是如何才能实现这一结果?

Scanner sc = new Scanner(System.in);

System.out.println("enter your string");
String text = sc.nextLine();

System.out.println("enter the character that will be repeated");
char character= sc.next().charAt(0);

System.out.println("enter the number of repetitions");
int repetitions = sc.nextInt();

for (int i = 0; i < text.length(); i++) {
    char z = text.charAt(i);
    if(z==character) {
         // repeat character in string put by user * repetitions 
    }
}
System.out.println(text);

4 个答案:

答案 0 :(得分:2)

如果您使用的是Java 8,则可以使用String.join并替换为:

String str = "dog";
int length = 4;
String s = "o";
str = str.replace(s, String.join("", Collections.nCopies(length, s)));// doooog

详细了解Collections::nCopies

答案 1 :(得分:0)

To complete your code, insert the following:

String ans="";
for (int i = 0; i < text.length(); i++) {
    char z = text.charAt(i);
    if(z==character) {
         for(int j=0;j<repetitions;j++)
            ans+=z;
    }
    else
        ans+=z;
}

However, there is a far more elegant way of doing this:

String replacement="";
for(int i=0;i<repetitions;i++)
    replacement+=character;
String ans = text.replaceAll(String.valueOf(character), replacement);

答案 2 :(得分:0)

The below should work:

StringBuilder buffer = new StringBuilder();
    for (int i = 0; i < text.length(); i++) {
                    char z = text.charAt(i);
                    if(z==character) {
                         // repeat character in string put by user * repetitions 
                        for (int j=1;j<=repetitions;j++){
                            buffer.append(z);
                        }
                    }else{
                         buffer.append(z);
                    }
                }
System.out.println(buffer.toString());

答案 3 :(得分:0)

If you are not using Java 8 you can try this.

StringBuilder builder = new StringBuilder();
String repetitionString = String.format("%" + repetitions + "s", character).replace(' ', character);
for (int i = 0; i < text.length(); i++) {
    char z = text.charAt(i);
    builder.append(z == character ? repetitionString : z);
}

text = builder.toString();
System.out.println(text);

In this solution we are using String.format for repeating the character that we want instead of a loop.

String.format("%" + repetitions + "s", z).replace(' ', z)

This is similar to what we can do in Python using the * operator, ie

z * repeatitions

which will repeat the character in z required number of times.

Another approach by which you can avoid the loops is using String.replace() method.

String repetitionString = String.format("%" + repetitions + "s", character).replace(' ', character);
text = text.replace(String.valueOf(character), repetitionString);
System.out.println(text);