Java String Multiplication [duplicate] - java

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Can I multiply strings in java to repeat sequences?
In Python, we can easily multiply the stings.
count = 10
print '*' * count
Is there any similar option available in Java?

You can use Dollar for your purposes(Java API that unifies collections, arrays, iterators/iterable, and char sequences.)
String str = $("*").repeat(count);
In this way you will get result "**********" as you want.
Java doesn't have that feature for now.

char[10] c = new char[10];
Arrays.fill(c, '*');
String str = new String(c);
To avoid creating a new String everytime.

How about this??
System.out.println(String.format("%10s", "").replace(' ', '*'));
This gives me output as **********.
I believe this is what you want...
Update 1
int yournumber = 10;
System.out.println(String.format("%" + yournumber + "s","*").replace(' ', '*'));
Good Luck!!!

The simplest way to do that in Java is to use a for() loop:
String s = "";
for (int i = 0; i < 10; i++) {
s += "*";
}
System.out.println(s);

Related

Is it possible to add integer values while concatenating Strings? [duplicate]

This question already has answers here:
concatenating string and numbers Java
(7 answers)
Closed 1 year ago.
Consider the following code (excerpt of main method):
String str = "The result: ";
int c = 5;
int k = 3;
System.out.println(str + c + k); // This would concatenate the all values, i.e. "The result: 53"
If the only thing allowed to be modified is within System.out.println(), is it possible to concatenate str to the sum of k and c?
Yes.
System.out.println(str + (c + k));
You can change order of execution by adding parentheses (same way as in math).
Indeed, as #talex said, you may use this single line code.
Yet, I think that this additude is a bit confusing, and may cause the code to be unreadable.
A better practice would be:
String str = "The result: ";
int c = 5;
int k = 3;
int result = c + k;
System.out.println(str + result);
This way, the code is more readable, and the order of execution will not confuse the programmers that read this code.
Yes
you should have use parentheses around sum of integers
System.out.println(str + (c + k));

Editing Unicode within a String

I wanted to have a List with Unicode Strings, but I wondered if I could use a for loop instead of adding 9 variables by hand. I tried the following code, but it didn't work.
List<String> reactions = new ArrayList<>();
for (int i = 1; i < 10; i++) {
reactions.add("\u003" + i + "\u20E3");
}
My IDEA gives me an 'illegal unicode escape' error.
Is there an other way to accomplish this?
The easiest way to convert a number to a character within a string is probably using a Formatter, via String.format:
List<String> reactions = new ArrayList<>();
for (int i = 1; i < 10; i++) {
reactions.add(String.format("%c\u20e3", 0x0030 + i));
}
Assuming you want to display the character \u003i, with ifrom 1 to 9, and \u20E3, remember a character is like a number and can be used in mathematical operation.
get the character \u0030: '\u0030'
add i : '\u0030' + i
concatenate the new character with the other one (as a string)
Then print the result:
System.out.println((char)('\u0030' + i) + "\u20E3");

Remove n number of dot(.) from String in Java [duplicate]

This question already has answers here:
Trim leading or trailing characters from a string?
(6 answers)
Closed 5 years ago.
I have the following string and I want to remove dynamic number of dot(.) at the end of the String.
"abc....."
Dot(.) can be more than one
Try this. It uses a regular expression to replace all dots at the end of your string with empty strings.
yourString.replaceAll("\\.+$", "");
Could do this to remove all .:
String a = "abc.....";
String new = a.replaceAll("[.]", "");
Remove just the trailing .'s:
String new = a.replaceAll("//.+$","");
Edit: Seeing the comment. To remove last n .'s
int dotsToRemove = 5; // whatever value n
String new = a.substring(0, s.length()-dotsToRemove);
how about using this function? seems to work faster than regex
public static String trimPoints(String txt)
{
char[] cs = txt.toCharArray();
int index =0;
for(int x =cs.length-1;x>=0;x--)
{
if(cs[x]=='.')
continue;
else
{
index = x+1;
break;
}
}
return txt.substring(0,index);
}

how to use java lambdas to append n number of chars to a string? [duplicate]

This question already has answers here:
Simple way to repeat a string
(32 answers)
Closed 5 years ago.
basically I'd like to see if there is a compact lambda way of doing this:
int n = ...
String s = "";
for (int i = 0; i < n; i++) {
s += 'a';
}
The start is easy, then I'm lost:
IntStream.range(0, n). ??
This is better:
String s = Stream.generate(() -> "a").limit(n).collect(Collectors.joining());
It is very straightforward;
int n = 20;
System.out.println(IntStream.range(0, n).boxed().map(i -> "a").collect(Collectors.joining()));
Prints out;
aaaaaaaaaaaaaaaaaaaa
You have to do boxed() to switch to a Integer stream, then just map each number to a "a" String, which will transform your stream of 1,2,3,4... to a,a,a,a,a... and finally join them.
Why use stream/lambda for this? Less efficient.
If you want a one-liner, try this instead:
String s = new String(new char[n]).replace('\0', 'a');

Convert ArrayList <Characters> into a String [duplicate]

This question already has answers here:
Converting ArrayList of Characters to a String?
(12 answers)
Closed 1 year ago.
Is there a simple way of converting an ArrayList that contains only characters into a string? So say we have
ArrayList<Character> arrayListChar = new ArrayList<Character>();
arrayListChar.add(a);
arrayListChar.add(b);
arrayListChar.add(c);
So the array list contains a, b, and c. Ideally what I'd want to do is turn that into a String "abc".
Iterator<Character> it = arrayListChar.iterator();
StringBuilder sb = new StringBuilder();
while(it.hasNext()) {
sb.append(it.next());
}
System.out.println(sb.toString());
You could use Apache Common Lang's StringUtils class. It has a join() function like you find in PHP.
Then the code:
StringUtils.join(arrayListChar, "")
would generate:
abc
int size = list.size();
char[] chars = new char[size];
for (int i = 0; i < size; i++) {
if (list.size() != size) {
throw new ConcurrentModificationException();
}
chars[i] = list.get(i);
}
String s = new String(chars);
Using regex magic:
String result = list.toString().replaceAll(", |\\[|\\]", "");
Get the String representation of the list, which is
[a, b, c]
and then remove the strings "[", "]", and ", ".
You can override it's toString method and implement the String formatting therein.
Override toString method of ArrayList or the better to extend the ArrayList class so that you may use old ArrayList toString() somewhere else in the code
String s = "";
for(Character i : arrayListChar)
s += i;
EDIT - as pointed out already, you should only use code like this if the number of strings to concatenate is small.

Categories