创建两个相同长度的字符串,一个复制另一个的结构,同时一遍又一遍地循环相同的字母



我有一个任意字符串"hello my name is timothy"和另一个任意"关键字"字符串"ham"。我想创建一个方法,通过反复重复其字符,同时保留空格,使第二个字符串与第一个字符串的长度相同,结构相同。结果是:"hamha mh amha mh amhamha。这是我到目前为止的代码:

    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;
}

上一个示例中的代码返回hamhamha ha ha。我该怎么解决这个问题?

首先,不要使用keyword += (string),使用StringBuilder更快。

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();
}

我会给你一些提示,但不是答案。这似乎是一堂很累人的课,所以你应该先自己试试。

  1. 您不应该处理作为方法参数的变量。在你的方法中,你正在处理keyword,因此改变了它。这不好。此外,您正在构建一个字符串。请阅读StringBuilder类的相关内容。

  2. 显然,您必须跟踪关键字的哪个字符应该放在输出的下一个字符中。你是怎么做到的?

  3. 您的for循环很好,因为您必须在整个输入字符串(此处为str)上循环,否则您将无法获得其结构。其他一切都发生在这个循环中。

你能用这些提示修复你的方法吗?

您的代码中需要一个类似于"循环迭代器"的关键字逻辑。因此,我使用自己的索引和模运算符来确保当它到达关键字的末尾时,它将从头开始。

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();
}
    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); 

将打印"hamha mh amha mh hamha"

问题是您只需向字符串"ham"中添加更多文本。这意味着,当您从"str"中的索引0开始时,在"keyword"中,您的第一个字符将位于索引str.length,在本例中为3。

如果使用新的字符串变量,则将从索引0开始。但是,当你试图访问"str"的索引i时,要注意边界感知的索引out,你必须使用模数来避免这种情况:

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;
}
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:哈姆哈
  2. I/p:字符串
   s1="Hello Aunt Mary";
   String s2="carl";

O/p:carlc arlc

适用于任何I/p..:)

您的程序应该是这个

public class Ham {
    public static String makeStringsEqual(String str, String keyword) {
        String ret = "";
        int spaces = 0;
        if (str.length() > keyword.length()) {
            for(int i = 0; i < str.length(); i++) {
                if (str.charAt(i) != ' ') {
                    ret += keyword.charAt((i - spaces) % keyword.length());
                } else {
                    spaces++;
                    ret += " ";
                }
            } 
        }
        return ret;
    }
    public static void main(String[] args) {
        System.out.println(makeStringsEqual("hello my name is timothy", "ham"));
    }
}

如果你不明白这里%是如何使用的,那么你可以有另一个版本(更简单的:)

public class Ham2 {
    public static String makeStringsEqual(String str, String keyword) {
        String ret = "";
        int ci     = 0; //current letter index in keyword
        if (str.length() > keyword.length()) {
            for(int i = 0; i < str.length(); i++) {
                if (str.charAt(i) != ' ') {
                    if (ci == keyword.length()) {
                        ci = 0;
                    }
                    ret += keyword.charAt(ci);
                    ci++;
                } else {
                    ret += " ";
                }
            } 
        }
        return ret;
    }
    public static void main(String[] args) {
        System.out.println(makeStringsEqual("hello my name is timothy", "ham"));
    }
}

只是为了练习,我尽可能使用Streams做了一个Java-8。

我欢迎各位提出意见/作出改进。

public void test() {
  // My string.
  String s = "Hello! My name is Timothy.";
  // The key loops around the string "ham"
  Iterator<Integer> k = Loop.of("ham", s.length());
  System.out.println(s);
  String result = s.codePoints()
          .map(c -> c == ' ' ? ' ' : k.next())
          .collect(StringBuilder::new,
                   StringBuilder::appendCodePoint,
                   StringBuilder::append)
          .toString();
  System.out.println(result);
}
static class Loop<T> implements Iterator<T> {
  // Where we are in the array.
  int i = 0;
  // The length to loop to.
  final int length;
  // The array to feed.
  final List<T> a;
  public Loop(List<T> a, int length) {
    this.a = a;
    this.length = length;
  }
  // Factories.
  private static Iterator<Integer> of(String s, int length) {
    List<Integer> a = new ArrayList(s.length());
    for (int i = 0; i < s.length(); i++) {
      a.add(s.codePointAt(i));
    }
    return new Loop(a, length);
  }
  @Override
  public boolean hasNext() {
    return i < length;
  }
  @Override
  public T next() {
    return a.get((i++) % a.size());
  }
}

打印

Hello! My name is Timothy.
hamham ha mham ha mhamhamh

最新更新