Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create two strings of same length, one duplicating the other's structure while looping the same letters over and over

Tags:

java

I have an arbitrary string "hello my name is timothy" and another arbitrary 'keyword' string "ham". I would like to create a method that would make the second string the same length as the first string and equal in structure, by repeating its characters over and over, while conserving the spaces. The result would be: "hamha mh amha mh amhamha. Here is my code so far:

    public String makeStringsEqual(String str, String keyword)
{
    if (str.length() > keyword.length())
    {
        for(int i = 0; i < str.length(); i++)
        {
            if (str.charAt(i) != ' ')
            {
                keyword += keyword.charAt(i);
            }
            else
                keyword += " ";
        }

    }
    return keyword;
}

The code with the previous example returns hamhamha ha ha. How can I fix this?

like image 538
user3044874 Avatar asked Nov 28 '13 08:11

user3044874


6 Answers

First of all, do not use keyword += (string), using a StringBuilder is faster.

public static String makeStringEqual(String str, String keyword) {
    StringBuilder sb = new StringBuilder("");
    if (str.length() > keyword.length()) {

        int j = 0; // this tells you what is the current index for the keyword
        for(int i=0;i<str.length();i++) {
            if (str.charAt(i) == ' ') {
                sb.append(' ');
            } else {
                sb.append(keyword.charAt(j));

                // when you use up a keyword's character, move on to the next char
                j++;

                // make sure to loop back to the start when you're at the end
                j %= keyword.length();
            }
        }
    }
    return sb.toString();
}
like image 80
aysonje Avatar answered Oct 17 '22 12:10

aysonje


I will give you some hints, but not the answer. It seems to be a lerning lesson, so you should first try it yourself.

  1. You should not work on a variable that is a method's parameter. In your method you are working on keyword, thus changing it. Not good. Additionally, you are building a string. Please go and read about the class StringBuilder.

  2. Obviously you must keep track of which character of the keyword should be placed next into the output. How could you achieve that?

  3. Your for loop is good, as you must loop over the entire input string (here str), because otherwise you would not get its structure. Everything else is taking place inside this loop.

Are you able to fix your method with these hints?

like image 42
Seelenvirtuose Avatar answered Oct 17 '22 13:10

Seelenvirtuose


You need an "looping iterator" like logic in your code for the keyword. Therefore I use an own index and the modulo operator to ensure that when it comes to the end of the keyword it will start from beginning.

public static String makeStringsEqual(String str, String keyword) {
    StringBuilder equalStringBuilder = new StringBuilder();
    if (str.length() > keyword.length()) {
        int keywordIndex = 0;
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) != ' ') {
                equalStringBuilder.append(keyword.charAt(keywordIndex++));
                keywordIndex %= keyword.length();
            } else {

                equalStringBuilder.append(' ');
            }
        }

    }
    return equalStringBuilder.toString();
}
like image 36
René Link Avatar answered Oct 17 '22 12:10

René Link


    String str = "hello my name is timothy";
    String keyword = "ham";

    String result = "";

    int i = 0;
    int j = 0;
    while (i < str.length()) {
        result += str.charAt(i) == ' ' ? ' ' : keyword.charAt(j++);
        if (j >= keyword.length()) j = 0;
        i++;
    }

    System.out.println(result); 

will print "hamha mh amha mh amhamha"

like image 40
Alexey Odintsov Avatar answered Oct 17 '22 14:10

Alexey Odintsov


The problem is that you just add more text to the string "ham". This means that while you start on index 0 in "str", in "keyword" your first character will be at index str.length, which in this case is 3.

If you use a new string variable, you will start at index 0. But watch out for indexoutofboundsexception when you try to access index i of "str", you would have to use modulus to avoid that:

public String makeStringsEqual(String str, String keyword)
{
    if (str.length() > keyword.length())
    {
        string result = "";
        for(int i = 0; i < str.length(); i++)
        {
            if (str.charAt(i) != ' ')
            {
                result += keyword.charAt(i % keyword.length());
            }
            else
                result += " ";
        }

    }
    return result;
}
like image 1
JanTheMan Avatar answered Oct 17 '22 14:10

JanTheMan


public static void main (String args[]){
       String s1="hello my name is timothy";
       String s2="ham";
       List al = new ArrayList();
       String s3="";
       int k=0;
       for(int i=0;i<s1.length();i++)
       {   if(k==s2.length())
       {
           k=0;
       }
           if(s1.charAt(i)==' ')
           {  s3=s3+" ";
               continue;
           }
           else
           {
               s3=s3+s2.charAt(k++);
           }

       }
       System.out.println(s3);
    }
  1. O/P : hamha mh amha mh amhamha
  2. I/p : String
   s1="Hello Aunt Mary";
   String s2="carl";

O/P : carlc arlc arlc

Works for any I/P .. :)

like image 1
TheLostMind Avatar answered Oct 17 '22 12:10

TheLostMind