How to insert one string into the middle of anothe

2020-02-16 06:12发布

I am trying to stick one string into the middle of another string, ex:

String One = "MonkeyPony";
String Two = "Monkey";

How would I put String Two into String One so it would read something like MonkeMonkeyyPony?

What I'm trying to do is insert "Monkey" into the middle of "MonkeyPony" numerous times, so on the first time it would read "MonkeMonkeyyPony", and on the second time it would read "MonkeMonMonkeykeyyPony", etc.

3条回答
欢心
2楼-- · 2020-02-16 06:28

You don't need to use StringBuilder or any other complex method to do this. Here is the simplest way to achieve this. In this method I have just used the simple String methods.

import java.util.Scanner;

class Insert
{
    public static void main(String[] args)
    {
        System.out.println("Enter First String");
        Scanner scan = new Scanner (System.in);
        String str = scan.next();
        System.out.println("Enter Second String");
        Scanner scan2 = new Scanner (System.in);
        String str1 = scan2.next();
        int i = str.length();
        int j = i/2;

        if (i % 2 == 0)                    //Condition For Even
        {
            System.out.println(str.substring(0,j) + str1 + str.substring(j-1,(str.length() - 1)));
        }
        else 
        {
            System.out.println(str.substring(0,j) + str1 + str.substring(j,(str.length() - 0)));
        }
    }
}
查看更多
唯我独甜
3楼-- · 2020-02-16 06:34

You have to concat two substrings of the first string onto the ends of the second.

// put the marble in the bag
public static String insert(String bag, String marble, int index) {
    String bagBegin = bag.substring(0,index);
    String bagEnd = bag.substring(index);
    return bagBegin + marble + bagEnd;
}
查看更多
▲ chillily
4楼-- · 2020-02-16 06:39

You can use StringBuilder.insert​(int offset, String str) to achieve this.

StringBuilder builder = new StringBuilder("MonkeyPony");
for(/* As often as necessary */) {
    int halfway = (int) (builder.length() / 2);
    builder.insert(halfway, "Monkey");
} return builder.toString();
查看更多
登录 后发表回答