Как умножить строки в java

Могу ли я умножить строки в Java для повторения последовательностей? [Дубликат]

Я хотел бы добавить i «0» в строку someNum . Есть ли у меня какой-то способ, чтобы я мог умножить строку, чтобы повторить ее, как это делает Python? Так что я мог бы просто пойти:

18 ответов

Самый простой способ в простой Java без зависимостей — это следующий однострочный:

new String(new char[generation]).replace("\0", "-") 

Замените генерацию числом повторений и «-» на строку (или char), которую вы хотите повторить.

Все это создает пустую строку, содержащую n чисел из 0x00 символов, а встроенный метод замены String # делает остальные.

Здесь образец для копирования и вставки:

public static String repeat(int count, String with) < return new String(new char[count]).replace("\0", 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"); >> 

Нет, но вы можете в Scala! (И затем скомпилируйте это и запустите его, используя любую реализацию Java. )

Теперь, если вы хотите сделать это простым способом в java, используйте пакет Apost commons-lang. Предполагая, что вы используете maven, добавьте эту зависимость в свой pom.xml:

  commons-lang commons-lang 2.4  

И затем используйте StringUtils.repeat следующим образом:

import org.apache.commons.lang.StringUtils . someNum = sumNum + StringUtils.repeat("0", 3); 

Вы должны сделать некоторые предположения, чтобы решить проблемы реального мира. В этом случае я использую Maven в моем текущем проекте. У меня есть pom.xml, настроенный с зависимостью commons-lang. Короче, мне было проще ответить на его вопрос. И я не совсем уверен, что бы я делал, если бы не использовал Maven — я думаю, мне нужно было бы создать собственное расположение для моих файлов JAR . аналогично хранилищу Maven! А затем включите эти файлы jar в мой путь к классам и выполняйте все виды работ, которые я хотел бы избежать. Если плакат действительно хочет взломать Java, то ей или ему нужно использовать Maven или его эквивалент. 🙂

Google Guava предоставляет другой способ сделать это с помощью Strings#repeat() :

String repeated = Strings.repeat("pete and re", 42); 

Приходят в голову два способа:

int i = 3; String someNum = "123"; // Way 1: char[] zeroes1 = new char[i]; Arrays.fill(zeroes1, '0'); String newNum1 = someNum + new String(zeroes1); System.out.println(newNum1); // 123000 // Way 2: String zeroes2 = String.format("%0" + i + "d", 0); String newNum2 = someNum + zeroes2; System.out.println(newNum2); // 123000 

Способ 2 может быть сокращен до:

someNum += String.format("%0" + i + "d", 0); System.out.println(someNum); // 123000 

Подробнее о String#format() можно найти в в своем API-документе и в java.util.Formatter .

Путь 1 работает только с одиночными символами, Путь 2 работает только с одиночным «0». Не совсем то, что я бы назвал общим решением проблемы .

Не уверен, о чем вы говорите, но это как минимум подходящее решение для собственной проблемы ОП 🙂 Если у вас есть проблема, задайте вопрос.

Если вы повторяете одиночные символы, такие как OP, и максимальное количество повторений не слишком велико, вы можете использовать простую операцию подстроки, например:

int i = 3; String someNum = "123"; someNum += "00000000000000000000".substring(0, i); 

Это не общий ответ, если вы спросите меня, если я хочу сделать «123» * 3, ваше решение не будет работать. Хорошо, это элегантно для одиночных символов, но это не гибкий 🙂

@Silviu Silviu Это не общий ответ, если вы спрашиваете кого-либо, и никто не спрашивал общего ответа. Мои вступительные комментарии касаются дел, на которые он работает, включая дело ОП.

Источник

Как умножить строку java

В Java мы не можем просто умножить строку на число n , чтобы повторить эту строку n раз. Чтобы повторить строку несколько раз в Java, можно использовать метод строки repeat() . Этот метод возвращает новую строку, значение которой является конкатенацией этой строки, повторенной энное количество раз. Например,

var word = "abc"; // Повторяем строку 3 раза var repeated = word.repeat(3); System.out.println(repeated); // => "abcabcabc" 

Источник

Multiply Strings in Java

Multiply Strings in Java

  1. Multiply Strings Using String().replace() in Java
  2. Multiply Strings Using the Stream API in Java
  3. Multiply Strings Using Guava in Java

In this tutorial, we will learn how we can multiply a string using several methods and examples.

Multiply Strings Using String().replace() in Java

The first method to multiply a string is to use the replace() function of the String class. This replace method accepts two arguments; the first one is the target, which is the string that we want to be replaced, and the second one is the replacement string.

String() takes an array of char and then formats them into a string. We can notice that we are replacing \0 with 0. Our goal is to multiply 0 10 times and join it to the end of 123 . \0 is called a null character, which finds the end of our string and replaces it with 0.

For the simplicity of the example, we have used a loop to see every step, but we can do it without the loop, and we will have a single string with all the 0’s multiplied.

public class Main   public static void main(String[] args)    for(int i = 0; i  10; i++)   String result = new String(new char[i]).replace("\0", "0");  System.out.println("123"+result);  >  > 
123 1230 12300 123000 1230000 12300000 123000000 1230000000 12300000000 123000000000 1230000000000 

Multiply Strings Using the Stream API in Java

We can use the Stream API introduced in Java 8 to multiply a string and then join them at the end of the string. In the example below, Stream.generate() is called to create new streams from the supplier; in our case, the supplier is ourString . limit() is used with the Stream to limit the number of values it must return.

The reduce() method is used to perform a binary operation and then return a single value. We are adding the elements and then returning the added value. We can notice that after all the operations, we get the result1 of Optional , which is returned when there is a chance that the result might be empty.

At last, we can check if the result1 is not empty by using isPresent() and then fetch the string using the get() method.

import java.util.Optional; import java.util.stream.Stream;  public class Main   public static void main(String[] args)    String ourString = "123";   for(int count = 0; count  10; count++)   OptionalString> result1 = Stream.generate(()-> ourString).limit(count).reduce((a, b) -> a + b);   String finalResult;  if (result1.isPresent())   finalResult = result1.get();  System.out.println(finalResult);  >  >  > > 
123 123123 123123123 123123123123 123123123123123 123123123123123123 123123123123123123123 123123123123123123123123 123123123123123123123123123 123123123123123123123123123123 

Multiply Strings Using Guava in Java

In the last method to multiply strings in Java, we will use a library called Guava . To use this library, we have to import it using the following maven dependency.

   com.google.guava   guava   30.0-jre  

Strings.repeat() method of the Guava library can be used to repeat the ourString multiple times. It takes two arguments, the string that we want to multiply and then the count of repetitions.

import com.google.common.base.Strings;  public class Main   public static void main(String[] args)    String ourString = "1234";  for(int count = 0; count  5; count++)   String finalResult = Strings.repeat(ourString, count);  System.out.println(finalResult);  >   > > 
1234 12341234 123412341234 1234123412341234 

Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.

Related Article — Java String

Copyright © 2023. All right reserved

Источник

How to Multiply String in Java

In this tutorial, we will learn how to multiply Strings in Java. We will multiply String by using String.repeat() and StringBuffer.append() method of Java. Let’s see some examples.

yes

To get the most out of this tutorial it is suggested that try all the code snippets and understand topics in a sequence.

Multiply string to repeat the sequence of characters.

String str = "StudyTonight"; String repeated = str.repeat(3);

The above code will support only Java 11 and above. Below that we need to use StringBuffer(). Why?

enlightened

Strings are immutable. It cannot be inherited, and once created, we can not alter the object.

Example

We are using the repeat() method of the String class to multiply strings and get a new string object.

public class StudyTonight < public static void main(String[] args) < String str = "Studytonight"; System.out.println( str.repeat(3) ); >>

Example of Multiply String Using StringBuffer.append()

We use StringBuffer() to do operation on String and later we can use StringBuffer.toString() method to change into String .

public class StudyTonight < public static void main(String[] args) < //original string String str = "studytonight "; //number of times repetition int n=5; //empty stringbuffer StringBuffer str_bfr = new StringBuffer(); for(int i=0;i//converting stringbuffer back to string using toString() method str = str_bfr.toString(); System.out.print(str); > >

studytonight studytonight studytonight studytonight studytonight

Example of Multiply String Using String.replace()

It is the shortest variant of the same code but requires Java 1.5 and above versions. The awesomeness of this code is no import or libraries needed. Where n is the number of times you want to repeat the string and str is the string to repeat.

public class StudyTonight < public static void main(String[] args) < String str = "studytonight "; int n=5; String repeated = new String(new char[n]).replace("\0", str); System.out.print(repeated); >>

studytonight studytonight studytonight studytonight studytonight

Conclusion

We can multiply string in java using appending a particular string in a loop using StringBuffer.append() and it will make sure that string is repeating n time. Another way is using String.replace() method where we pass null character («\0») which is also known as an end of a string and the second parameter as a replacement of that character by the original string. String.repeat() is also able to perform the same reputation of String.

Источник

Читайте также:  Json decode аналог php
Оцените статью