* for strings in Java [duplicate] - java

This question already has answers here:
Simple way to repeat a string
(32 answers)
Closed 1 year ago.
In Python, there is a * operator for strings, I'm not sure what it's called but it does this:
>>> "h" * 9
"hhhhhhhhh"
Is there an operator in Java like Python's *?

Many libraries have such utility methods.
E.g. Guava:
String s = Strings.repeat("*",9);
or Apache Commons / Lang:
String s = StringUtils.repeat("*", 9);
Both of these classes also have methods to pad a String's beginning or end to a certain length with a specified character.

I think the easiest way to do this in java is with a loop:
String string = "";
for(int i=0; i<9; i++)
{
string+="h";
}

you can use something like this :
String str = "abc";
String repeated = StringUtils.repeat(str, 3);
repeated.equals("abcabcabc");

There is no such operator in Java, but you can use Arrays.fill() or Apache Commons StringUtils.repeat() to achieve that result:
Assuming
char src = 'x';
String out;
with Arrays.fill()
char[] arr = new char[10] ;
Arrays.fill(arr,src);
out = new String(arr);
with StringUtils.repeat()
out = StringUtils.repeat(src, 10);

seems to be a repeat operator
Use apache libraries (common-lang) : Stringutils.repeat(str, nb)

String.repeat(count) has been available since JDK 11. String.repeat(count)

There is no operator like that, but you could assign the sting "h" to a variable and use a for loop to print the variable a desired amount of times.

Related

Character Concatenation Resulting in Numerical Output [duplicate]

This question already has answers here:
In Java, is the result of the addition of two chars an int or a char?
(8 answers)
Closed 9 years ago.
In a programming language called Java, I have the following line of code:
char u = 'U';
System.out.print(u + 'X');
This statement results in an output like this:
173
Instead of
UX
Am I missing something? Why isn't it outputing 'UX'? Thank you.
Because you are performing an addition of chars. In Java, when you add chars, they are first converted to integers. In your case, the ASCII code of U is 85 and the code for X is 88.
And you print the sum, which is 173.
If you want to concatenate the chars, you can do, for example:
System.out.print("" + u + 'X');
Now the + is not a char addition any more, it becomes a String concatenation (because the first parameter "" is a String).
You could also create the String from its characters:
char[] characters = {u, 'X'};
System.out.print(new String(characters));
In this language known as Java, the result of adding two chars, shorts, or bytes is an int.
Thus, the integer value of U (85) is added to the integer value of X (88) and you get an integer value of 173 (85+88).
To Fix:
You'll probably want to make u a string. A string plus a char will be a string, as will a string plus a string.
String u = "U"; // u is a string
System.out.print(u + 'X'); // string plus a char is a string
String u = "U";
System.out.print(u + "X");
instead of char type use String class or StringBuilder class
Another way to convert one of the characters to a string:
char u = 'U';
System.out.print(Character.toString(u) + 'X');
This way could be useful when your variable is of type char for a good reason and you can't easily redeclare it as a String.
That "language called Java" bit amused me.
A quick search for "java concatenate" (which I recommend you do now and every time you have a question) revealed that most good Java programmers hate using + for concatenation. Even if it isn't used numerically when you want string concatenation, like in your code, it is also slow.
It seems that a much better way is to create a StringBuffer object and then call its append method for each string you want to be concatenated to it. See here: http://www.ibm.com/developerworks/websphere/library/bestpractices/string_concatenation.html

Looking for easy way in java to uppper case only the first letter of a string [duplicate]

This question already has answers here:
How to capitalize the first character of each word in a string
(51 answers)
Closed 9 years ago.
Looking for easy way in java to change only the first letter to upper case of a string.
For example, I have a String DRIVER, how can I make it Driver with java
You could try this:
String d = "DRIVER";
d = d.substring(0,1) + d.substring(1).toLowerCase();
Edit:
see also StringUtils.capitalize(), like so:
d = StringUtils.capitalize(d.toLowerCase());
WordUtils.capitalize(string);
http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/text/WordUtils.html
String str = "DRIVER";
String strFirst = str.substring(0,1);
str = strFirst + str.substring(1).toLowerCase();
public static void main(String[] args) {
String txt = "DRIVER";
txt = txt.substring(0,1).toUpperCase() + txt.substring(1).toLowerCase();
System.out.print(txt);
}
I would use CapitalizeFully()
String s = "DRIVER";
WordUtils.capitalizeFully(s);
s would hold "Driver"
capitalize() only changes the first character to a capital, it doesn't touch the others.
I understand CapitalizeFully() changes the first char to a capitol and the other to a lower case.
https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/text/WordUtils.html#capitalizeFully(java.lang.String)
By the way there are lots of other great functions in the Apache Commons Lang Library.
I am using Springs so I can do:
String d = "DRIVER";
d = StringUtils.capitalize(d.toLowerCase());

Repeating a string in Java - similar to Python's one line simplicity [duplicate]

This question already has answers here:
Simple way to repeat a string
(32 answers)
Can I multiply strings in Java to repeat sequences? [duplicate]
(19 answers)
Closed 9 years ago.
I am a new to java coming from python.
I am wondering how I can multiply a string in java.
In python I would do this:
str1 = "hello"
str2 = str1 * 10
string 2 now has the value:
#str2 == 'hellohellohellohellohellohellohellohellohellohello'
I was wondering what the simplest way is to achieve this in java. Do I have to use a for loop or is there a built in method?
EDIT 1
Thanks for your responses I have since found an elegant solution to my problem:
str2 = new String(new char[10]).replace("\0", "hello");
note: this answer was originally posted by user102008 here: https://stackoverflow.com/a/4903603
Although not built-in, Guava has a short way of doing this using Strings:
str2 = Strings.repeat("hello", 10);
You can use a StringBuffer.
String str1 = "hello";
StringBuffer buffer = new StringBuffer(str1);
for (int i = 0; i < 10; i++) {
buffer.append(str1);
}
str2 = buffer.toString();
Refer to http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/StringBuffer.html for documentation.
If you're not going to use any threads, you can use StringBuilder which sort of works the same way as StringBuffer but is not thread-safe. Refer to http://javahowto.blogspot.ca/2006/08/stringbuilder-vs-stringbuffer.html for more details (thanks TheCapn)
The for loop is probably your best bet here:
for (int i = 0; i < 10; i++)
str2 += "hello";
If you are doing a lot of iterations (in the 100+ range) consider the use of a StringBuilder object as each time you modify the string you are allocating new memory and releasing the old string for garbage collection. In cases where you are doing this a considerable amount of times it will be a performance issue.
I don't think there is a way to do that without some sort of loop.
For example:
String result = "";
for (int i=0; i<10; i++){
result += "hello";
}

Java Split String Using Delimiter [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Matching a “.” in java
I have a String 1.2.4 which i want to split and get 2 to compare it with another String that i get.
I am trying to do the following
StringTokenizer old_ver = new StringTokenizer(oldVersion, ".");
int oldVer = Integer.parseInt(old_ver.nextToken());
oldVer = Integer.parseInt(old_ver.nextToken());
StringTokenizer new_ver = new StringTokenizer(newVersion, ".");
int newVer = Integer.parseInt(new_ver.nextToken());
newVer = Integer.parseInt(new_ver.nextToken());
if (oldVer == newVer) {
return true;
}
IS there a better way to do it using .Split()
The problemis that in Regex "." is a single character. Hence, you need to escape it using "\\."
Similarly, you can use
string.split("\\.");
EDIT:
split() method of the String class uses Pattern and Matcher internally which is normally the API used for Regex in Java.
So there is no problem going with split.
In your code, 1.2.1 would be "compatible" with 3.2.0, and this looks like a serious problem, regardless if you use String.split or not. Also, you do not need to parse version numbers into integers as you only compare for equality.
StringTokenizer old_ver = new StringTokenizer(oldVersion, ".");
StringTokenizer new_ver = new StringTokenizer(newVersion, ".");
return (old_ver.nextToken().equals(new_ver.nextToken() &&
old_ver.nextToken().equals(new_ver.nextToken() );
You can surely do with String.split as well:
String [] oldV = String.split(oldVersion,"\\.");
String [] newV = String.split(newVersion,"\\.");
return oldV[0].equals(newV[0]) && oldV[1].equals(newV[1]);
The String.split() version seems slightly shorter but but for me it looks slightly more difficult to read because:
It involves additional thinking step that dot (.) is a reserved char and must be escaped.
"Next element and then following element" seems involving less thinking effort than "element at position 0 and then element at position 1".
It may pay to have some version comparator that first compares major, then intermediate and then minor parts of the version number the way that we could have the tests like "1.2.4 or later".

Pad digits until string is 8 chars long in java?

i was reading and couldn't find quite the snippet. I am looking for a function that takes in a string and left pads zeros (0) until the entire string is 8 digits long. All the other snippets i find only lets the integer control how much to pad and not how much to pad until the entire string is x digits long. in java.
Example
BC238 => 000BC289
4 => 00000004
etc thanks.
If you're starting with a string that you know is <= 8 characters long, you can do something like this:
s = "00000000".substring(0, 8 - s.length()) + s;
Actually, this works as well:
s = "00000000".substring(s.length()) + s;
If you're not sure that s is at most 8 characters long, you need to test it before using either of the above (or use Math.min(8, s.length()) or be prepared to catch an IndexOutOfBoundsException).
If you're starting with an integer and want to convert it to hex with padding, you can do this:
String s = String.format("%08x", Integer.valueOf(val));
org.apache.commons.lang.StringUtils.leftPad(String str, int size, char padChar)
You can take a look here
How about this:
s = (s.length()) < 8 ? ("00000000".substring(s.length()) + s) : s;
or
s = "00000000".substring(Math.min(8, s.length())) + s;
I prefer using an existing library method though, such as a method from Apache Commons StringUtils, or String.format(...). The intent of your code is clearer if you use a library method, assuming it is has a sensible name.
The lazy way is to use something like: Right("00000000" + yourstring, 8) with simple implementations of the Right function available here: http://geekswithblogs.net/congsuco/archive/2005/07/07/45607.aspx

Categories

Resources