2

I'm a beginner with java and one concept is rather unclear to me. I need to create a method that creates a new string by replicating another string. For example, if the String1 is "java" and it is specified that it needs to be repeated 4 times and each of them needs to be separated with a comma, the new string would look like this: java, java, java, java

However, the method should not print it, but only create a new string that is then printed in the main program. This is a problem for me, because I have trouble understanding, how can I use a loop to create something without printing it. I think that the following code would print it correctly:

public static void replicate(String str, int times) {
   for (int i = 0; i < times; i++) {
      System.out.print(str);
      if (i < times -1) {
         System.out.print(", ");
      }
   }
}

How could I transform it so that I could use the method to create a new string without printing it? I am assuming this is something super simple, but I just don't know at all how to do this, because every guide just uses examples of printing in these kinds of situations.

0

5 Answers 5

4

This is much better with Collections and join

import java.util.*;
public class Main 
{
    public static void main(String[] args) 
    {


        String newstr=String.join(",", Collections.nCopies(3, "java"));
        System.out.println(newstr);
    }
}

Working fiddle-https://repl.it/repls/OfficialInvolvedObject

Sign up to request clarification or add additional context in comments.

Comments

2

The following code should be useful for academic purposes in which you cannot use all of Java's libraries. You want to use a variable to store the repeated text and then return that variable to the main method for it to be printed. For non academic purposes or in cases when efficiency is a priority the java.lang.StringBuilder object should be used.

 public static String replicate(String str, int times) {
    String newString = "";
    for (int i = 0; i < times; i++) {
        newString = newString + str;
        if(i<times-1){
            newString = newString + ", ";
        }
    }
    return newString;
}

Comments

2

This is easy to do using the StringBuilder class, which can be used like this:

public static String replicate(String str, int times) {
   StringBuilder builder = new StringBuilder();

   for (int i = 0; i < times; i++) {
      builder.append(str);
      if (i < times - 1) {
         builder.append(", ");
      }
   }

   return builder.toString();
}

Comments

1

One option is to use a StringBuilder, as exemplified by Emily's answer. Since the same delimiter is used each time another option is to use java.util.StringJoiner. Here's an example:

public static String replicate(String str, int times) {
  StringJoiner joiner = new StringJoiner(", ");
  for (int i = 0; i < times; i++) {
    joiner.add(str);
  }
  return joiner.toString();
}

Comments

0

I am assuming this is something super simple

You are right. While the other answers show various helper classes, you can do it with re-assigning a single String variable already:

public static String replicate(String str, int times) {
   String result="";
   for (int i = 0; i < times; i++) {
      result += str; //System.out.print(str);
      if (i < times -1) {
         result += ", "; //System.out.print(", ");
      }
   }
   return result;
}

Or, if you do not worry about having to provide 0 copies:

public static String replicate(String str, int times) {
   String result=str; // one copy, without comma
   for (int i = 1; i < times; i++) {
      result += ", " + str; // all the other copies have their commas
   }
   return result;
}

This latter "trick" can be used with StringBuilder too of course:

public static String replicate(String str, int times) {
   StringBuilder result = new StringBuilder(str);
   for (int i = 1; i < times; i++) {
      result.append(", ");
      result.append(str);
   }
   return result.toString();
}

Btw, it may be worth mentioning what there story about StringBuilder is: when Java sees something=string1+string2, internally it writes StringBuilder temp=new StringBuilder(string1); temp.append(string2); something=temp.toString() (of course it is an unnamed, internal variable, not "temp"). So a brand new StringBuilder object is created, appended, converted back to a brand new String and thrown away every time. That is why the suggested method is to have one, dedicated StringBuilder, use it many times, and get the result from it only once, at the end.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.