How Do I Concatenate Characters to the Beginning of a String? - java

I have the following statement: binaryOutput = y % 2 + binaryOutput;
I want to the value of y % 2 to be added at the very beginning of binaryOutput. Is there a better way to do this operation than the way I did it? I feel like my method is a little redundant.
Edit: binaryOutput is a String object. y is an integer.

USe the insert method of StringBuilder:
_sb.insert(0, "Hello ");

Related

How to increment a number in a String in Java?

I want to increment a number in a string in Java 8.
Like this:
String lifes = "3";
lifes--
But i know that way is impossible, does you know other way to do it?
Integer.parseInt("3") + 1
The above statement results 4 which means we are parsing the String value as Integer and then incrementing in here, hope it helps!
If the string only contains the number, I'd do something like this -
lifes = String.valueOf(Integer.parseInt(lifes) - 1);

How to remove the letters from float value in android?

I have some issue like this
in my textview Rs. 99.99
String val = textview.getText().toString();
Result :: val :: Rs.99.99
i am converting that into float using this way
float value = Float.parseFloat(val);
i am getting NumberFormatException: Rs.99.99 cannot convert
any one guide me
You can do the following before converting it to float
String substring = str.length() > 2 ? str.substring(str.length() - 3) : str;
You can try this way.
System.out.println(Float.parseFloat("Rs.99.99".substring(3)));
Note: You need to make sure the string always contain "Rs." in the beginning.
i am getting numberFormat Exception Rs.99.99 cannot convert
Yes, because in method
Float.parseFloat(String s);
You get
NumberFormatException -- if the string does not contain a parsable float.
And In your case it isn't,
So best option is to apply Validation to enter only floating point numbers inside text View.
It's not entirely clear what the problem is (do all the strings that cause problems begin with Rs., or are users putting other kinds of garbage at the beginning of the input)? Here's a way to remove all characters from the string, up to (but not including) the first digit:
val = val.replaceFirst("^[^0-9]*", "");
This finds the first occurrence of a pattern that starts at the beginning of the string (the first ^) and consists of 0 or more occurrences of nondigits ([^0-9]).

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

Variable widths in Java's String.format method

I'm working on a project in which I need to display textual trees. I'm trying to use Java's String.format method to simplify the formatting process, but I ran into trouble when trying to apply variable widths.
Current I have a variable (an int) which is called depth.
I try to do the following:
String.format("%"+depth+"s"," ") + getOriginalText() + "\n";
However I get the following error.
java.util.FormatFlagsConversionMismatchException: Conversion = s, Flags = 0
Any suggestions on how to do this, or should I just settle for loops?
Thanks for the help!
This works:
int depth = 5;
String str= "Hello"+ String.format("%"+depth+"s"," ") + "world" + "\n";
System.out.println(str);
It prints 5 while spaces in between.
Hello World.
Please check you code and make sure that depth is assigned with a valid int value. Most likely that (invalid value in depth) is the problem.
You could try the following using "System.out.printf" command:
int depth = 10;
System.out.printf("%s" + "%" +depth + "s", "Hello","World" );
Hello    World

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