Integer to String conversion methods - java

What are the alternative methods for converting and integer to a string?

Integer.toString(your_int_value);
or
your_int_value+"";
and, of course, Java Docs should be best friend in this case.

String one = Integer.toString(1);

String myString = Integer.toString(myInt);

Here are all the different versions:
a) Convert an Integer to a String
Integer one = Integer.valueOf(1);
String oneAsString = one.toString();
b) Convert an int to a String
int one = 1;
String oneAsString = String.valueOf(one);
c) Convert a String to an Integer
String oneAsString = "1";
Integer one = Integer.valueOf(oneAsString);
d) Convert a String to an int
String oneAsString = "1";
int one = Integer.parseInt(oneAsString);
There is also a page in the Sun Java tutorial called Converting between Numbers and Strings.

String.valueOf(anyInt);

There is Integer.toString() or you can use string concatenation where 1st operand is string (even empty): String snr = "" + nr;. This can be useful if you want to add more items to String variable.

You can use String.valueOf(thenumber) for conversion. But if you plan to add another word converting is not nessesary. You can have something like this:
String string = "Number: " + 1
This will make the string equal Number: 1.

Related

How can I concatanate a string from an int and a char?

For example I want to concatanate char a ='A' and int b = 5 into string = "A5".
String string = a + b; doesn't work.
You may want to use StringBuilder, where you can append any type of primitives :
char a ='A';
int b = 5;
StringBuilder sb = new StringBuilder();
sb.append(a);
sb.append(b);
String result = sb.toString();
The easiest way for me is to precede the String with an empty String.
String str = "" + 'a' + 10;
The conversion goes from left to right so you start out with a String.
If you do it this way,
String str = 'a' + 10 + "";
you will get a String value of "107" since the numeric addition is done before the conversion to a String.
One way to convert most primitive values to String is to utilize the overloaded method in the String class valueOf():
public static void main(String[] args)
{
char a = 'A';
int b = 5;
String str = String.valueOf(a) + b; //Can do either of these two lines, will work the same
String str2 = a + String.valueOf(b);
System.out.println(str);
System.out.println(str2);
}
You only need to convert one of the values into String, because appending them afterward will automatically convert the other into a String.
This method will work on both char, and int in this scenario, but will also work on long, double, float and boolean as well. This is identical to calling Integer.toString(int i) or Character.toString(i) etc... but it is convenient to be able to use the same overloaded method for each case instead of requiring to call methods from different classes.
To all the answers already given I provide one that explain why "it doesn´t work" as you expect. A string is nothing but an immutable collection of char. A char itself is nothing but a (signed) integer and thus can implicitely converted to such. Thus when you write char+ int an integer-operation occurs, in your case A + 5 which results in 70, because ASCII-code for A is 65.
Last but not least String s = 70 surely does not compile, because a number can´t be converted to a string.
So you have to tell the compiler that you do not want an integer-operation, but a string-concatenation, which is by turning one of the operands into a string already:
String s = 'A'.toString() + 5
or
String s = 'A' + 5.toString()

Converting a string of digits into their hex equivalents

I tried this
String dataC = Integer.toHexString(dataB);
But of course that wouldn't work with a string...
toHexString requires integer as argument, so how about changing string of digits to integer first?
String dataC = Integer.toHexString(Integer.parseInt(dataB));
(more readable code)
int dataBInteger = Integer.parseInt(dataB);
String dataC = Integer.toHexString(dataBInteger);
If value from string is in range of long (-9223372036854775808; 9223372036854775807) you can use
String dataC = Long.toHexString(Long.parseLong(dataB));
If you don't want to assume any limit of number of digits you can use BigInteger
BigInteger bi = new BigInteger(dataB);
String dataC = bi.toString(16);
You should first convert dataB string to int:
int number = Integer.parseInt(dataB);
String dataC = "0x" + Integer.toHexString(number);
As it's a long string, try
String hex = new BigInteger(dec).toString(16);

converts parts of a string to int in java

I was wondering how can I take some numbers in a string and convert them to an integer type? for example if a user entered 12:15pm how can I get 1 and 2 and make an int with value 12?
Given the example above, you could try something like this:
final int value = Integer.parseInt(input.substring(0, input.indexOf(':'))); //value = 12
Where input = 12:15pm in this case.
Generally speaking, just use a combination of String#indexOf(String), String#substring(int, int) and Integer.parseInt(String).
Read the String and Integer API's
You can use the String.split() to get the two numeric strings
You can use Integer.parseInt(...) to convert the String to an int.
Edit: Using the split() you can do something like:
String time = "12:34pm";
int hour = Integer.parseInt( time.split(":")[0] );

Converting strings to integers and adding them in Java

I have 4 strings:
str1 = 10110011;(length of all string is:32)
str2 = 00110000;
str3 = 01011000;
str4 = 11110000;
In my project I have to add these string and the result should be:
result[1] = str1[1]+str2[1]+str3[1]+str4[1];
result should be obtained as addition of integer numbers.
For the example above, result = 22341011
I know integer to string conversion in Java is very easy but I found string to integer conversion a little harder.
To parse Integers -2^31 < n < 2^31-1 use:
Integer value = Integer.valueOf("10110011");
For numbers that are larger, use the BigInteger class:
BigInteger value1 = new BigInteger("101100111011001110110011101100111011001110110011");
BigInteger value2 = // etc
BigInteger result = value1.add(value2).add(value3); //etc.
The simplest way to do this is with Integer.parseInt(str1). Returns an int containing the value represented by the string.
valueOf() returns an Integer object, rather than an int primitive.
Because your numbers are so big they will not fit in an int. Use the BigInteger class.
I am not known about your project and what actually your problem is. But I came to guess from your partial information that, you have multiple set of strings in bit representation as you explained.
str1 = "1000110.....11";
str1 = "1110110.....01"; etc
adding those decimal values,gives an ambiguous result as an integer can be the sum of multiple integer values. Just see an example below where there are total 5 possibilities[with positive decimal values] to yield 6.
1+5 = 6;
2+4 = 6;
3+3 = 6;
4+2 = 6;
5+1 = 6;
If you proceed in that way you just do an error,nothing else in your case.
One better solution can be,
compute the decimal values of individual strings. Instead of adding(+) them, just concat(join) them to form a single string.
I am suggesting this approach because, This gives always a unique value and later you may need to know individual strings decimal values.
String strVal1 = String.format(computeDecimal(str1));
String strVal2 = String.format(computeDecimal(str2));
String strVal3 = String.format(computeDecimal(str3));
.
.
.
String strValn = String.format(computeDecimal(strn));
String myVal = String.concate(strVal1,strVal1,strVal1,....strValn);
Now you can treat your string as your wish.
//This will give you a non conflicting result.
Better to implement above approach than BigIntegers.
Hope this helps you greatly.

Split a string all alpha and all numeric

I have a List and I would like to split the first two characters (alpha characters) into a different string and then all the numbers that follow (they vary in length).
How could I do that?
String wholeString == "AB4578";
String alpha; // this has to be AB
String num; // this has to be 4578
Thank you very much in advance!
Tested and works:
String wholeString = "AB4578";
String alpha = null;
String num = null;
for (int i = 0; i < wholeString.length(); i++) {
if (wholeString.charAt(i) < 65) {
alpha = wholeString.substring(0, i);
num = wholeString.substring(i);
break;
}
}
With this approach both the A-z part and the 0-9 part can vary in size, it might not be very effective though considering it's calling charAt(...) for every char in the String.
Hope this helps.
String wholeString = "AB4578";
String alpha = wholeString.substring(0,2);
String num = wholeString.substring(2);
Must See
String.substring(int, int)
If the format is the same, then the answer is already provided. But if the format is not same than you can convert the string into char array and check each character against the ASCII values to check if it is an alphabet or a number.
char[] ch=wholestring.toCharArray();
Now you can apply a for loop for checking each character individually.
for(int l=0; l<ch.length;l++)
{
//code to check the characters
}
And you can separate both types in different strings using StringBuilder or forming two char arrays and then converting them to strings using
String.valueOf(chArray);
ASCII values - http://www.asciitable.com/
Try using the substring method for Strings.
Example:
String alpha = wholeString.substring(0,2);
String num = wholeString.substring(2);
http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#substring%28int%29
If the format is always the same you can just do this:
String wholeString = "AB4578";
String alpha = wholeString.substring(0, 2);
String num = wholeString.substring(2);
Recommend String API. You would need to use substring operations.

Categories