1

I am trying to stick one string into the middle of another string, and then put Monkey into the middle of the new string.

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

Basically 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" on the second time it would read "MonkeMonMonkeykeyyPony", etc.

Kent
  • 189,393
  • 32
  • 233
  • 301
user2150807
  • 411
  • 2
  • 7
  • 14

4 Answers4

4

Use a StringBuilder:

StringBuilder builder = new StringBuilder(One);
for (int i = 0; i < 10; ++i) {
  builder.insert(builder.length() / 2, Two);
  System.out.println(builder.toString());
}
Arne Burmeister
  • 20,046
  • 8
  • 53
  • 94
0

You can try this:

One = One.substr(0,One.length()/2)+Two+One.substr(One.length()/2+1, One.length();

The first element in the string concatenation takes the first half of the string One, and then you concatenate with thw word Two, and then add the rest of the one.

yrazlik
  • 10,411
  • 33
  • 99
  • 165
  • I think i gave the answer in c++ but i am not sure if you are using c++ or java? Similar member functions exist in java and you can find them – yrazlik Mar 15 '13 at 23:18
0

I don't know this question is from your real work or is homework/ interview algorithm question.

The straightforward solution would be calculating the index of original string, inserting the new string to that position. Do this n times.

I just write an idea, not sure if it is ok: say we want to do insert 100(n) times

  • first we take the string two, the Monkey
  • build two strings, one is "Mon" repeated 99 times (n-1), and the other one is "key", also repeat 99 times
  • find out the insertion index of string ONE, say i
  • insert this string to i position: 99Mons + String TWO("Monkey") + 99keys

I am not sure if this is a good way to go...


Did a small test:

I am curious about the performance of my solution, so I did a small performance test, with the straightforward solution from @Ame Burmeister.

In my test:

  • Tests are done with Junit Test class
  • StopWatch is from guava
  • warming up 4 times before measuring elapsed time, to avoid Jit
  • the two methods give same output (with smaller n), both are correctly implemented.
  • Both tested with 100000 Insertions

The straightforward solution (Basically just copy from @Ame's answer)

@Test
    public void insertWithBuilder() {
        final int n = 100000;
        final String one = "MonkeyPony";
        final String two = "Monkey";

        final Stopwatch sw = new Stopwatch();
        int x = 1;
        for (; x <= 5; x++) {// loop 4 times (warming up) to avoid JIT
            if (x == 5) {
                sw.start();
            }
            final StringBuilder builder = new StringBuilder(one);
            System.out.println("warming up times:" + x);
            for (int i = 0; i < n; ++i) {
                builder.insert(builder.length() / 2, two);
            }
            if (x == 5) {
                sw.stop();
                // System.out.println("builder:" + builder.toString());
            }
        }
        System.out.println("SBuilder:" + sw.elapsedTime(TimeUnit.MILLISECONDS));
    }

The implmentation from my idea:

@Test
    public void insertWithRepeatString() {
        final int n = 100000;
        final String one = "MonkeyPony";
        final String two = "Monkey";

        final Stopwatch sw = new Stopwatch();
        int x = 1;
        for (; x <= 5; x++) { // loop 4 times (warming up) to avoid JIT
            System.out.println("warming up times:" + x);
            if (x == 5) {
                sw.start();
            }
            final StringBuilder builder = new StringBuilder(one);
            final int m = two.length() / 2;
            final String h1 = two.substring(0, m); //get Mon
            final String r1 = two.substring(m);    //get Key
            final String head = new String(new char[n - 1]).replace("\0", h1); //build repeat string
            final String tail = new String(new char[n - 1]).replace("\0", r1); //build repeat String
            final StringBuilder builder2 = new StringBuilder(head);
            builder2.append(two).append(tail);
            builder.insert(builder.length() / 2, builder2);
            if (x == 5) {
                sw.stop();
                // System.out.println("builder:" + builder.toString());
            }
        }
        System.out.println("Idea:" + sw.elapsedTime(TimeUnit.MILLISECONDS));
    }

The output:

warming up times:1
warming up times:2
warming up times:3
warming up times:4
warming up times:5
Idea:41
warming up times:1
warming up times:2
warming up times:3
warming up times:4
warming up times:5
SBuilder:4413 
Kent
  • 189,393
  • 32
  • 233
  • 301
  • Not sure how to go about doing that, I feel like there is a simpler way to do this but I'm not quite sure. Maybe calculating the string length, dividing by 2, then inserting the new string at that position? I'm not the best at java so I'm not sure if that functionality exists. – user2150807 Mar 15 '13 at 23:49
  • @user2150807 I added a performance test, to compare to the straightforward solution from Arne Burmeister. The result turns out that there is BIG difference. I hope I did the test right. – Kent Mar 16 '13 at 01:19
  • Of course my approach is slower. Your idea is elegant and fast but not as easy to understand. The question is from Rep 11, so I thought about a simple solution ;-) – Arne Burmeister Mar 16 '13 at 17:16
  • @ArneBurmeister as I said, I don't know where is the question from. If it is an interview question, I would answer like what in my answer. however if it is a problem in real project, and `n` is not that big, I would do the same as yours. unless this method would be called thousand times. – Kent Mar 16 '13 at 17:26
0

This solution may be simple, but it'll consume enormous amount of time while comparring with others.
substring method has been utilized here.

import java.util.Scanner;

public class test {

     public static void main(String[] args) {

         int n=0;
         String str1,str2=null;


         Scanner in = new Scanner(System.in);

         System.out.println("Enter the String1.!");
         str1=in.nextLine();

         System.out.println("Enter the String2.!");
         str2=in.nextLine();

         System.out.println("Enter the Count.!"); 
         n=Integer.parseInt(in.nextLine());

         in.close();

         for(int i=0;i<n;i++)
         {
             //Concept: Say str1=TEST str2=123, Now the below code will do this TE + 123 + ST 
             str1=str1.substring(0,str1.length()/2) + str2 + str1.substring(str1.length()/2);
             System.out.println(str1);
         }


        }


}
Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130