Config Router

  • Google Sheets
  • CCNA Online training
    • CCNA
  • CISCO Lab Guides
    • CCNA Security Lab Manual With Solutions
    • CCNP Route Lab Manual with Solutions
    • CCNP Switch Lab Manual with Solutions
  • Juniper
  • Linux
  • DevOps Tutorials
  • Python Array
You are here: Home / Can I multiply strings in Java to repeat sequences? [duplicate]

Can I multiply strings in Java to repeat sequences? [duplicate]

August 16, 2021 by James Palmer

The easiest way in plain Java with no dependencies is the following one-liner:
new String(new char[generation]).replace(“”, “-“)

Replace generation with number of repetitions, and the “-” with the string (or char) you want repeated.
All this does is create an empty string containing n number of 0x00 characters, and the built-in String#replace method does the rest.
Here’s a sample to copy and paste:
public static String repeat(int count, String with) {
return new String(new char[count]).replace(“”, with);
}

public static String repeat(int count) {
return repeat(count, ” “);
}

public static void main(String[] args) {
for (int n = 0; n < 10; n++) { System.out.println(repeat(n) + " Hello"); } for (int n = 0; n < 10; n++) { System.out.println(repeat(n, ":-) ") + " Hello"); } } No, but you can in Scala! (And then compile that and run it using any Java implementation!!!!) Now, if you want to do it the easy way in java, use the Apache commons-lang package. Assuming you're using maven, add this dependency to your pom.xml:
commons-lang
commons-lang
2.4

And then use StringUtils.repeat as follows:
import org.apache.commons.lang.StringUtils
…
someNum = sumNum + StringUtils.repeat(“0”, 3);

Related

Filed Under: Uncategorized

Recent Posts

  • How do I give user access to Jenkins?
  • What is docker volume command?
  • What is the date format in Unix?
  • What is the difference between ARG and ENV Docker?
  • What is rsync command Linux?
  • How to Add Music to Snapchat 2021 Android? | How to Search, Add, Share Songs on Snapchat Story?
  • How to Enable Snapchat Notifications for Android & iPhone? | Steps to Turn on Snapchat Bitmoji Notification
  • Easy Methods to Fix Snapchat Camera Not Working Black Screen Issue | Reasons & Troubleshooting Tips to Solve Snapchat Camera Problems
  • Detailed Procedure for How to Update Snapchat on iOS 14 for Free
  • What is Snapchat Spotlight Feature? How to Make a Spotlight on Snapchat?
  • Snapchat Hack Tutorial 2021: Can I hack a Snapchat Account without them knowing?

Copyright © 2025 · News Pro Theme on Genesis Framework · WordPress · Log in