Java: String - add character n-times [duplicate] - java

This question already has answers here:
Simple way to repeat a string
(32 answers)
Closed 4 years ago.
Is there a simple way to add a character or another String n-times to an existing String?
I couldn’t find anything in String, Stringbuilder, etc.

Apache commons-lang3 has StringUtils.repeat(String, int), with this one you can do (for simplicity, not with StringBuilder):
String original;
original = original + StringUtils.repeat("x", n);
Since it is open source, you can read how it is written. There is a minor optimalization for small n-s if I remember correctly, but most of the time it uses StringBuilder.

In case of Java 8 you can do:
int n = 4;
String existing = "...";
String result = existing + String.join("", Collections.nCopies(n, "*"));
Output:
...****
In Java 8 the String.join method was added. But Collections.nCopies is even in Java 5.

You are able to do this using Java 8 stream APIs. The following code creates the string "cccc" from "c":
String s = "c";
int n = 4;
String sRepeated = IntStream.range(0, n).mapToObj(i -> s).collect(Collectors.joining(""));

For the case of repeating a single character (not a String), you could use Arrays.fill:
String original = "original ";
char c = 'c';
int number = 9;
char[] repeat = new char[number];
Arrays.fill(repeat, c);
original += new String(repeat);

Use this:
String input = "original";
String newStr = "new"; //new string to be added
int n = 10 // no of times we want to add
input = input + new String(new char[n]).replace("\0", newStr);

You can use Guava's Strings.repeat method:
String existingString = ...
existingString += Strings.repeat("foo", n);

for(int i = 0; i < n; i++) {
existing_string += 'c';
}
but you should use StringBuilder instead, and save memory
int n = 3;
String existing_string = "string";
StringBuilder builder = new StringBuilder(existing_string);
for (int i = 0; i < n; i++) {
builder.append(" append ");
}
System.out.println(builder.toString());

Its better to use StringBuilder instead of String because String is an immutable class and it cannot be modified once created: in String each concatenation results in creating a new instance of the String class with the modified string.

In addition to the answers above, you should initialize the StringBuilder with an appropriate capacity, especially that you already know it. For example:
int capacity = existingString.length() + n * appendableString.length();
StringBuilder builder = new StringBuilder(capacity);

public String appendNewStringToExisting(String exisitingString, String newString, int number) {
StringBuilder builder = new StringBuilder(exisitingString);
for(int iDx = 0; iDx < number; iDx++){
builder.append(newString);
}
return builder.toString();
}

String toAdd = "toAdd";
StringBuilder s = new StringBuilder();
for(int count = 0; count < MAX; count++) {
s.append(toAdd);
}
String output = s.toString();

Keep in mind that if the "n" is large, it might not be such a great idea to use +=, since every time you add another String through +=, the JVM will create a brand new object (plenty of info on this around).
Something like:
StringBuilder b = new StringBuilder(existing_string);
for(int i = 0; i<n; i++){
b.append("other_string");
}
return b.toString();
Not actually coding this in an IDE, so minor flaws may occur, but this is the basic idea.

How I did it:
final int numberOfSpaces = 22;
final char[] spaceArray = new char[numberOfSpaces];
Arrays.fill(spaces, ' ');
Now add it to your StringBuilder
stringBuilder.append(spaceArray);
or String
final String spaces = String.valueOf(spaceArray);

To have an idea of the speed penalty, I have tested two versions, one with Array.fill and one with StringBuilder.
public static String repeat(char what, int howmany) {
char[] chars = new char[howmany];
Arrays.fill(chars, what);
return new String(chars);
}
and
public static String repeatSB(char what, int howmany) {
StringBuilder out = new StringBuilder(howmany);
for (int i = 0; i < howmany; i++)
out.append(what);
return out.toString();
}
using
public static void main(String... args) {
String res;
long time;
for (int j = 0; j < 1000; j++) {
res = repeat(' ', 100000);
res = repeatSB(' ', 100000);
}
time = System.nanoTime();
res = repeat(' ', 100000);
time = System.nanoTime() - time;
System.out.println("elapsed repeat: " + time);
time = System.nanoTime();
res = repeatSB(' ', 100000);
time = System.nanoTime() - time;
System.out.println("elapsed repeatSB: " + time);
}
(note the loop in main function is to kick in JIT)
The results are as follows:
elapsed repeat: 65899
elapsed repeatSB: 305171
It is a huge difference

Here is a simple way..
for(int i=0;i<n;i++)
{
yourString = yourString + "what you want to append continiously";
}

Related

(Java) Append elements to a String variable from String array up to specific index?

public class sample {
public static void main(String[] args) {
String[] test = new String[1024];
int count = 0;
test[count] = "33";
count++;
test[count] = "34";
String s = new String();
This is just a simplified version, but I would like to append elements to a String variable s up to the index value of count without using StringBuilder, is there a way to do it? Thank you.
edit: without using loop as well, is there a String manipulation function I can use?
One way to do that is using String.join and Arrays.copyOf:
String s = String.join("", Arrays.copyOf(test, count + 1));
Which, with your test data, produces 3334
Dont quite understand what you want...
But I guess you could user char array?
char[] c = new char[maxCount]
for(int i = 0;i<maxCount;i++){
c[i] = "34";
}
String s = String.valueOf(c)
Hope this could help you:)
Hard to say, what you're asking for...
Concatenating consecutive numbers could be easily done with a stream:
String s = IntStream.rangeClosed(0, 1024)
.mapToObj(Integer::toString)
.collect(Collectors.joining());
We can use the join function of String.
Assuming the test is the string array.
String joinedString = String.join("", Arrays.stream(test).limit(count).collect(Collectors.toList()))
You can use String.join()
public class Main {
public static void main(String[] args) {
String[] test = new String[1024];
int count = 0;
test[count] = "33";
count++;
test[count] = "34";
String s = new String();
System.out.println(s=String.join("", Arrays.copyOf(test, count + 1)));
}
}

Best way to concatenate Strings in java(Time efficiency)

I checked many discutions about the best way to concatenate many string In Java.
As i understood Stringbuilder is more efficient than the + operator.
Unfortunantly My question is a litlle bit different.
Given the string :"AAAAA", how can we concatenate it with n times the char '_',knowing that the '_' has to come before the String "AAAAA"
if n is equal to 3 and str="AAAAA", the result has to be the String "___AAAAA"
String str = "AAAAA";
for (int i=0;i<100;i++){
str="_"+str;
}
In my program i have a Longs String , so i have to use the efficient way.
Thank you
EDIT1:
As I have read some Solutions I discovered that I asked for Only One Case , SO I arrived to this Solution that i think is good:
public class Concatenation {
public static void main(String[] args) {
//so str is the String that i want to modify
StringBuilder str = new StringBuilder("AAAAA");
//As suggested
StringBuilder space = new StringBuilder();
for (int i = 0; i < 3; i++) {
space.append("_");
}
//another for loop to concatenate different char and not only the '_'
for (int i = 0; i < 3; i++) {
char next = getTheNewchar();
space.append(next);
}
space.append(str);
str = space;
System.out.println(str);
}
public static char getTheNewchar(){
//normally i return a rondom char, but for the case of simplicity i return the same char
return 'A';
}
}
Best way to concatenate Strings in Java: You don't.... Strings are immutable in Java. Each time you concatenate, you generate a new Object. Use StringBuilder instead.
StringBuilder sb = new StringBuilder();
for (int i=0;i<100;i++){
sb.append("_");
}
sb.append("AAAAA");
String str = sb.toString();
Go to char array, alloting the right size, fill the array, and sum it up back into a string.
Can’t beat that.
public String concat(char c, int l, String string) {
int sl = string.length();
char[] buf = new char[sl + l];
int pos = 0;
for (int i = 0; i < l; i++) {
buf[pos++] = c;
}
for (int i = 0; i < sl; i++) {
buf[pos++] = string.charAt(i);
}
return String.valueOf(buf);
}
I'd do something like:
import java.util.Arrays;
...
int numUnderbars = 3;
char[] underbarArray = new char[numUnderbars];
Arrays.fill(underbarArray, '_');
String output = String.valueOf(underbarArray) + "AAAA";
but the reality is that any of the solutions presented would likely be trivially different in run time.
If you do not like to write for loop use
org.apache.commons.lang.StringUtils class repeat(str,n) method.
Your code will be shorter:
String str=new StringBuilder(StringUtils.repeat("_",n)).append("AAAAA").toString();
BTW:
Actual answer to the question is in the code of that repeat method.
when 1 or 2 characters need to be repeated it uses char array in the loop, otherwise it uses StringBuilder append solution.

Flip a Hex String

Acording to a other question made here Split a Hex String without spaces and flip it, I write this new question more clearly here.
I have an Hex String like this:
Hex_string = 2B00FFEC
What I need is to change the order of the Hex String to start from the latest characters, so this would be like this:
Fliped_hex_string = ECFF002B
In the other question I asked a way to achieve this using the .split() method. But there should be another way to get this in a better way.
As simple as you can is
String s = "2B00FFEC";
StringBuilder result = new StringBuilder();
for (int i = 0; i <=s.length()-2; i=i+2) {
result.append(new StringBuilder(s.substring(i,i+2)).reverse());
}
System.out.println(result.reverse().toString()); //op :ECFF002B
OP constrains the character length to exactly 8 characters in comments.
A purely numeric answer (inspired from idioms to convert endianness); saves going to and from strings
n is an int:
int m = ((n>>24)&0xff) | // byte 3 to byte 0
((n<<8)&0xff0000) | // byte 1 to byte 2
((n>>8)&0xff00) | // byte 2 to byte 1
((n<<24)&0xff000000); // byte 0 to byte 3
If you need to convert this to hexadecimal, use
String s = Integer.toHexString(m);
and if you need to set n from hexadecimal, use
int n = (int)Long.parseLong(hex_string, 16);
where hex_string is your initial string. You need to go via the Long parser to allow for negatives.
You could do something like:
String a = "456789AB";
char[] ca = a.toCharArray();
StringBuilder sb = new StringBuilder(a.length());
for (int i = 0; i<a.length();i+=2)
{
sb.insert(0, ca, i, 2);
}
This also extends to longer Strings if needed
Perhaps you should try something as simple as this:
public static String flip(final String hex){
final StringBuilder builder = new StringBuilder(hex.length());
for(int i = hex.length(); i > 1; i-=2)
builder.append(hex.substring(i-2, i));
return builder.toString();
}
public static void main(String args[]){
System.out.println(flip("2B00FFEC"));
}
The output is: ECFF002B
Next time you ask a question, perhaps you should show us some code you've written used in order to solve your problem (and then ask us why your code doesn't work, not your problem). You will not learn anything from us just providing answers without you knowing how they work.
This method seems to do what you want
String changeHexOrder(String s) {
char[] arr = s.toCharArray();
char tmp;
//change positions of [i, i + 1 , , , , , ,length - i - 2, length - i - 1]
for (int i = 0; i < arr.length / 2; i += 2) {
tmp = arr[i];
arr[i] = arr[arr.length-i-2];
arr[arr.length-i-2] = tmp;
tmp = arr[i+1];
arr[i+1] = arr[arr.length-i-1];
arr[arr.length-i-1] = tmp;
}
return new String(arr);
}
This worked for me
StringBuilder lsbToMsb=new StringBuilder();
for(int i=input.length();i>0;i-=2)
{
lsbMsb.append(lsbToMsb.substring(i-2,i));
}
String lsbMsb=lsbMsb.toString();

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

This question already has answers here:
Simple way to repeat a string
(32 answers)
Closed 4 years ago.
I have something like the following:
int i = 3;
String someNum = "123";
I'd like to append i "0"s to the someNum string. Does it have some way I can multiply a string to repeat it like Python does?
So I could just go:
someNum = sumNum + ("0" * 3);
or something similar?
Where, in this case, my final result would be:
"123000".
The easiest way in plain Java with no dependencies is the following one-liner:
new String(new char[generation]).replace("\0", "-")
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("\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");
}
}
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:
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.4</version>
</dependency>
And then use StringUtils.repeat as follows:
import org.apache.commons.lang.StringUtils
...
someNum = sumNum + StringUtils.repeat("0", 3);
String::repeat
Use String::repeat in Java 11 and later.
Examples
"A".repeat( 3 )
AAA
And the example from the Question.
int i = 3; //frequency to repeat
String someNum = "123"; // initial string
String ch = "0"; // character to append
someNum = someNum + ch.repeat(i); // formulation of the string
System.out.println(someNum); // would result in output -- "123000"
Google Guava provides another way to do this with Strings#repeat():
String repeated = Strings.repeat("pete and re", 42);
Two ways comes to mind:
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
Way 2 can be shortened to:
someNum += String.format("%0" + i + "d", 0);
System.out.println(someNum); // 123000
More about String#format() is available in its API doc and the one of java.util.Formatter.
If you're repeating single characters like the OP, and the maximum number of repeats is not too high, then you could use a simple substring operation like this:
int i = 3;
String someNum = "123";
someNum += "00000000000000000000".substring(0, i);
No. Java does not have this feature. You'd have to create your String using a StringBuilder, and a loop of some sort.
Simple way of doing this.
private String repeatString(String s,int count){
StringBuilder r = new StringBuilder();
for (int i = 0; i < count; i++) {
r.append(s);
}
return r.toString();
}
Java 8 provides a way (albeit a little clunky). As a method:
public static String repeat(String s, int n) {
return Stream.generate(() -> s).limit(n).collect(Collectors.joining(""));
}
or less efficient, but nicer looking IMHO:
public static String repeat(String s, int n) {
return Stream.generate(() -> s).limit(n).reduce((a, b) -> a + b);
}
I created a method that do the same thing you want, feel free to try this:
public String repeat(String s, int count) {
return count > 0 ? s + repeat(s, --count) : "";
}
with Dollar:
String s = "123" + $("0").repeat(3); // 123000
I don't believe Java natively provides this feature, although it would be nice. I write Perl code occasionally and the x operator in Perl comes in really handy for repeating strings!
However StringUtils in commons-lang provides this feature. The method is called repeat(). Your only other option is to build it manually using a loop.
With Guava:
Joiner.on("").join(Collections.nCopies(i, someNum));
No, you can't. However you can use this function to repeat a character.
public String repeat(char c, int times){
StringBuffer b = new StringBuffer();
for(int i=0;i < times;i++){
b.append(c);
}
return b.toString();
}
Disclaimer: I typed it here. Might have mistakes.
A generalisation of Dave Hartnoll's answer (I am mainly taking the concept ad absurdum, maybe don't use that in anything where you need speed).
This allows one to fill the String up with i characters following a given pattern.
int i = 3;
String someNum = "123";
String pattern = "789";
someNum += "00000000000000000000".replaceAll("0",pattern).substring(0, i);
If you don't need a pattern but just any single character you can use that (it's a tad faster):
int i = 3;
String someNum = "123";
char c = "7";
someNum += "00000000000000000000".replaceAll("0",c).substring(0, i);
Similar to what has already been said:
public String multStuff(String first, String toAdd, int amount) {
String append = "";
for (int i = 1; i <= amount; i++) {
append += toAdd;
}
return first + append;
}
Input multStuff("123", "0", 3);
Output "123000"
we can create multiply strings using * in python but not in java you can use for loop in your case:
String sample="123";
for(int i=0;i<3;i++)
{
sample=+"0";
}
There's no shortcut for doing this in Java like the example you gave in Python.
You'd have to do this:
for (;i > 0; i--) {
somenum = somenum + "0";
}
The simplest way is:
String someNum = "123000";
System.out.println(someNum);

How to reverse a string

I need to reverse the string of a user's input.
I need it done in the simplest of ways. I was trying to do reverseOrder(UserInput) but it wasn't working.
For example, user inputs abc I just take the string and print out cba
new StringBuilder(str).reverse().toString()
java.util.Collections.reverseOrder is for sorting in reverse of normal order.
I prefer using Apache's commons-lang for this kind of thing. There are all kinds of goodies, including:
StringUtils.reverse("Hello World!");
yields: !dlroW olleH
StringUtils.reverseDelimited("Hello World!", ' ');
yields: World! Hello
If you are new to programming, which I guess you are, my suggestion is "Why use simple stuff?".
Understand the internals and play some!!
public static void main(String[] args) {
String str = "abcasz";
char[] orgArr = str.toCharArray();
char[] revArr = new char[orgArr.length];
for (int i = 0; i < orgArr.length;i++) {
revArr[i] = orgArr[orgArr.length - 1 - i];
}
String revStr = new String(revArr);
System.out.println(revStr);
There is an interesting method to do it so too.
String input = "abc";
//Here, input is String to reverse
int b = input.length();
String reverse = ""; // Declaring reverse String variable
while(b!=0){
//Loop for switching between the characters of the String input
reverse += (input.charAt(b-1));
b--;
}
System.out.println(reverse);
public String reverseString(final String input_String)
{
char temp;
char[] chars = input_String.toCharArray();
int N = chars.length;
for (int i = 0 ; i < (N / 2) ; i++)
{
temp = chars[i];
chars[i] = chars[N - 1 - i];
chars[N - 1 - i] = temp;
}
return new String(chars);
}
Run :
Pandora
arodnaP
Without going through the char sequence, easiest way:
public String reverse(String post) {
String backward = "";
for(int i = post.length() - 1; i >= 0; i--) {
backward = backward + post.substring(i, i + 1);
}
return backward;
}

Categories