Pad digits until string is 8 chars long in java? - 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

Related

Converting from Int to Hex in Delphi and Java

I have to convert the following Delphi code to Java:
function IntToHex(MyValue: Integer; MinimumWidth: Integer): Ansistring;
begin
AnsiStrings.FmtStr(Result, '%.*x', [MyValue, MinimumWidth]);
end;
The IntToHex function converts a DecimalValue integer into a hexadecimal format string of at least MinimumWidth characters wide.
I've implemented it in Java as:
public static String intToHex(int value)
{
return Integer.toHexString(value);
}
Do I need in Java to indicate that the resulting string must contain at least the specified number of digits like in Delphi with parameter MinimumWidth?
Did I already with my Java function implemented the full functionality from the Delphi IntToHeX-function?
If I correctly understand your question, I think your solution should be to use String.format in Java
If you want hex numbers in the string you can use
String myFormattedString = String.format("%x", mynumber);
You can specify the lenght prepending it to the x, as
String myFormattedString = String.format("%4x", mynumber);
Where of course mynumber is a int or any other kind of valid number.
If you want to pad with zeros you should use
String myFormattedString = String.format("%04x", mynumber);
You can use capital X to have capital letters in the resulting String
To have more information on the format option you can take a look at the following URL: http://docs.oracle.com/javase/6/docs/api/java/util/Formatter.html#syntax
Hope this can help

Converting an integer and a character to a string in java

I'm trying to create a string comprised of a single letter, followed by 4 digits e.g. b6789. I'm getting stuck when I try to convert a character, and integer to one String. I can't use toString() because I've overwritten it, and I assume that concatenation is not the best way to approach it? This was my solution, until I realised that valueof() only takes a single parameter. Any suggestions? FYI - I'm using Random, because I will be creating multiples at some point. The rest of my code seemed irrelevant, and hence has been omitted.
Random r = new Random();
Integer numbers = r.nextInt(9000) + 1000;
Character letter = (char)(r.nextInt(26) + 'a');
String strRep = String.valueOf(letter, numbers);
I think they mean for you not to use concatenation with + operator.
Rather than that, there's a class called StringBuilder which will do the trick for you. Just create an empty one, append anything you need on it (takes Objects or primitives as arguments and does all the work for you), and at the end, just call at its "toString()" method, and you'll have your concatenated String.
For example
StringBuilder sb = new StringBuilder();
sb.append("Foo");
sb.append(123);
return sb.toString();
would return the string Foo123
you can use:
Character.toString(char)
which is
String.valueOf(char)
in reality which also works.
or just use
String str = "" + 'a';
as already mentioned but not very efficient as it is
String str = new StringBuilder().append("").append('a').toString();
in reality.
same goes for integer + string or char + int to string. I think your simpliest way would be to use string concatenation
Looks like you want
String.valueOf(letter).concat(numbers.toString());

Java inline method/strategy for truncating String?

If I have a String:
String neatish = getTheString(); // returns "...neat..."
I know that I can get rid of the first ellipsis using:
getTheString().substring(3);
But I'm wondering if there's a similar one-line method that takes the end off, based on length? Like:
getTheString().substring(3).truncate(3);
I don't want a character-specific method, ie. one that works only on ellipses.
While there's a substring() that accepts two parameters, it requires the altering String to be saved off to a variable first to determine the length. (Or, you can call getTheString() twice.)
I can certainly write one, but I'm wondering if there is a one-line method either in the standard java.lang package, or in Apache Commons-Lang, that will accomplish this.
I'm 50% curious, and 50% avoiding re-inventing the wheel.
Update: To avoid confusion, I do not want:
String neatish = getTheString();
neatish = neatish.substring(3)...;
I'm instead looking for the back-end version of substring(), and wondering why there isn't one.
Fun exercise
String theString = new StringBuilder(getTheString()).delete(0, 3).reverse().delete(0, 3).reverse().toString();
Get the String into a StringBuilder, remove the first 3 chars, reverse it, remove the last 3 chars (which are now at the start), reverse it again.
You can use subStringBefore and subStringAfter from Commons:
StringUtils.subStringAfter(StringUtils.subStringBefore(getTheString(), "..."), "...");
EDIT based on length:
You need: StringUtils.html#substring(java.lang.String, int, int)
StringUtils.substring(getTheString(), 3, -3);
getTheString().substring(3).replaceFirst("(?s)...$", "");
getTheString().replaceFirst("(?s)^...(.*)...$", "$1");
This removes the last 3 chars by a regular expression, where (?s) make . also match newlines. Use \\. to match a period. UGLY.
You could write a method to do it.
public static String trimChar(String s, char ch) {
int start = 0;
for(; start < s.length(); start++)
if (s.charAt(start) != ch)
break;
int end = s.length();
for(; end > start; end--)
if (s.charAt(end-1) != ch)
break;
return s.substring(start, end);
}
String s = trimChar(getTheString(), '.');

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

* for strings in Java [duplicate]

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.

Categories

Resources