How to convert an integer value to string? - java

How do I convert an integer variable to a string variable in Java?

you can either use
String.valueOf(intVarable)
or
Integer.toString(intVarable)

There are at least three ways to do it. Two have already been pointed out:
String s = String.valueOf(i);
String s = Integer.toString(i);
Another more concise way is:
String s = "" + i;
See it working online: ideone
This is particularly useful if the reason you are converting the integer to a string is in order to concatenate it to another string, as it means you can omit the explicit conversion:
System.out.println("The value of i is: " + i);

Here is the method manually convert the int to String value.Anyone correct me if i did wrong.
/**
* #param a
* #return
*/
private String convertToString(int a) {
int c;
char m;
StringBuilder ans = new StringBuilder();
// convert the String to int
while (a > 0) {
c = a % 10;
a = a / 10;
m = (char) ('0' + c);
ans.append(m);
}
return ans.reverse().toString();
}

Integer yourInt;
yourInt = 3;
String yourString = yourInt.toString();

There are many different type of wat to convert Integer value to string
// for example i =10
1) String.valueOf(i);//Now it will return "10"
2 String s=Integer.toString(i);//Now it will return "10"
3) StringBuilder string = string.append(i).toString();
//i = any integer nuber
4) String string = "" + i;
5) StringBuilder string = string.append(i).toString();
6) String million = String.format("%d", 1000000)

Related

Split String from the last iteration

This post is an update to this one : get specific character in a string with regex and remove unused zero
In the first place, i wanted to remove with an regular expression the unused zero in the last match.
I found that the regular expression is a bit overkill for what i need.
Here is what i would like now,
I would like to use split() method
to get from this :
String myString = "2020-LI50532-3329-00100"
this :
String data1 = "2020"
String data2 = "LI50532"
String data3 = "3329"
String data4 = "00100"
So then i can remove from the LAST data the unused Zero
to convert "00100" in "100"
And then concatenate all the data to get this
"2020-LI50532-3329-100"
Im not familiar with the split method, if anyone can enlight me about this ^^
You can use substring method to get rid of the leading zeros...
String myString = "2020-LI50532-3329-00100";
String[] data = myString.split("-");
data[3] = data[3].substring(2);
StringBuilder sb = new StringBuilder();
sb.append(data[0] + "-" + data[1] + "-" + data[2] + "-" + data[3]);
String result = sb.toString();
System.out.println(result);
Assuming that we want to remove the leading zeroes of ONLY the last block, maybe we can:
Extract the last block
Convert it to Integer and back to String to remove leading zeroes
Replace the last block with the String obtained in above step
Something like this:
public String removeLeadingZeroesFromLastBlock(String text) {
int indexOfLastDelimiter = text.lastIndexOf('-');
if (indexOfLastDelimiter >= 0) {
String lastBlock = text.substring(indexOfLastDelimiter + 1);
String lastBlockWithoutLeadingZeroes = String.valueOf(Integer.valueOf(lastBlock)); // will throw exception if last block is not an int
return text.substring(0, indexOfLastDelimiter + 1).concat(lastBlockWithoutLeadingZeroes);
}
return text;
}
Solution using regex:
public class Main {
public static void main(String[] args) {
// Test
System.out.println(parse("2020-LI50532-3329-00100"));
System.out.println(parse("2020-LI50532-3329-00001"));
System.out.println(parse("2020-LI50532-03329-00100"));
System.out.println(parse("2020-LI50532-03329-00001"));
}
static String parse(String str) {
return str.replaceAll("0+(?=[1-9]\\d*$)", "");
}
}
Output:
2020-LI50532-3329-100
2020-LI50532-3329-1
2020-LI50532-03329-100
2020-LI50532-03329-1
Explanation of the regex:
One or more zeros followed by a non-zero digit which can be optionally followed by any digit(s) until the end of the string (specified by $).
Solution without using regex:
You can do it also by using Integer.parseInt which can parse a string like 00100 into 100.
public class Main {
public static void main(String[] args) {
// Test
System.out.println(parse("2020-LI50532-3329-00100"));
System.out.println(parse("2020-LI50532-3329-00001"));
System.out.println(parse("2020-LI50532-03329-00100"));
System.out.println(parse("2020-LI50532-03329-00001"));
}
static String parse(String str) {
String[] parts = str.split("-");
try {
parts[parts.length - 1] = String.valueOf(Integer.parseInt(parts[parts.length - 1]));
} catch (NumberFormatException e) {
// Do nothing
}
return String.join("-", parts);
}
}
Output:
2020-LI50532-3329-100
2020-LI50532-3329-1
2020-LI50532-03329-100
2020-LI50532-03329-1
you can convert the last string portion to integer type like below for removing unused zeros:
String myString = "2020-LI50532-3329-00100";
String[] data = myString.split("-");
data[3] = data[3].substring(2);
StringBuilder sb = new StringBuilder();
sb.append(data[0] + "-" + data[1] + "-" + data[2] + "-" + Integer.parseInt(data[3]));
String result = sb.toString();
System.out.println(result);
You should avoid String manipulation where possible and rely on existing types in the Java language. One such type is the Integer. It looks like your code consists of 4 parts - Year (Integer) - String - Integer - Integer.
So to properly validate it I would use the following code:
Scanner scan = new Scanner("2020-LI50532-3329-00100");
scan.useDelimiter("-");
Integer firstPart = scan.nextInt();
String secondPart = scan.next();
Integer thirdPart = scan.nextInt();
Integer fourthPart = scan.nextInt();
Or alternatively something like:
String str = "00100";
int num = Integer.parseInt(str);
System.out.println(num);
If you want to reconstruct your original value, you should probably use a NumberFormat to add the missing 0s.
The main points are:
Always try to reuse existing code and tools available in your language
Always try to use available types (LocalDate, Integer, Long)
Create your own types (classes) and use the expressiveness of the Object Oriented language
public class Test {
public static void main(String[] args) {
System.out.println(trimLeadingZeroesFromLastPart("2020-LI50532-03329-00100"));
}
private static String trimLeadingZeroesFromLastPart(String input) {
String delem = "-";
String result = "";
if (input != null && !input.isEmpty()) {
String[] data = input.split(delem);
StringBuilder tempStrBldr = new StringBuilder();
for (int idx = 0; idx < data.length; idx++) {
if (idx == data.length - 1) {
tempStrBldr.append(trimLeadingZeroes(data[idx]));
} else {
tempStrBldr.append(data[idx]);
}
tempStrBldr.append(delem);
}
result = tempStrBldr.substring(0, tempStrBldr.length() - 1);
}
return result;
}
private static String trimLeadingZeroes(String input) {
int idx;
for (idx = 0; idx < input.length() - 1; idx++) {
if (input.charAt(idx) != '0') {
break;
}
}
return input.substring(idx);
}
}
Output:
2020-LI50532-3329-100

How to insert char at specific location throughout the string? [duplicate]

I'm getting in an int with a 6 digit value. I want to display it as a String with a decimal point (.) at 2 digits from the end of int. I wanted to use a float but was suggested to use String for a better display output (instead of 1234.5 will be 1234.50). Therefore, I need a function that will take an int as parameter and return the properly formatted String with a decimal point 2 digits from the end.
Say:
int j= 123456
Integer.toString(j);
//processing...
//output : 1234.56
As mentioned in comments, a StringBuilder is probably a faster implementation than using a StringBuffer. As mentioned in the Java docs:
This class provides an API compatible with StringBuffer, but with no guarantee of synchronization. This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.
Usage :
String str = Integer.toString(j);
str = new StringBuilder(str).insert(str.length()-2, ".").toString();
Or if you need synchronization use the StringBuffer with similar usage :
String str = Integer.toString(j);
str = new StringBuffer(str).insert(str.length()-2, ".").toString();
int j = 123456;
String x = Integer.toString(j);
x = x.substring(0, 4) + "." + x.substring(4, x.length());
int yourInteger = 123450;
String s = String.format("%6.2f", yourInteger / 100.0);
System.out.println(s);
Using ApacheCommons3 StringUtils, you could also do
int j = 123456;
String s = Integer.toString(j);
int pos = s.length()-2;
s = StringUtils.overlay(s,".", pos, pos);
it's basically substring concatenation but shorter if you don't mind using libraries, or already depending on StringUtils
In most use-cases, using a StringBuilder (as already answered) is a good way to do this. However, if performance matters, this may be a good alternative.
/**
* Insert the 'insert' String at the index 'position' into the 'target' String.
*
* ````
* insertAt("AC", 0, "") -> "AC"
* insertAt("AC", 1, "xxx") -> "AxxxC"
* insertAt("AB", 2, "C") -> "ABC
* ````
*/
public static String insertAt(final String target, final int position, final String insert) {
final int targetLen = target.length();
if (position < 0 || position > targetLen) {
throw new IllegalArgumentException("position=" + position);
}
if (insert.isEmpty()) {
return target;
}
if (position == 0) {
return insert.concat(target);
} else if (position == targetLen) {
return target.concat(insert);
}
final int insertLen = insert.length();
final char[] buffer = new char[targetLen + insertLen];
target.getChars(0, position, buffer, 0);
insert.getChars(0, insertLen, buffer, position);
target.getChars(position, targetLen, buffer, position + insertLen);
return new String(buffer);
}
For Kotlin dudes ;) from the accepted answer (#MikeThomsen's)
fun String.insert(insertAt: Int, string: String): String {
return this.substring(0, insertAt) + string + this.substring(insertAt, this.length)
}
Test ✅
"ThisTest".insert(insertAt = 4, string = "Is").should.equal("ThisIsTest")
String.format("%0d.%02d", d / 100, d % 100);
You could use
System.out.printf("%4.2f%n", ((float)12345)/100));
As per the comments, 12345/100.0 would be better, as would the use of double instead of float.
If you are using a system where float is expensive (e.g. no FPU) or not allowed (e.g. in accounting) you could use something like this:
for (int i = 1; i < 100000; i *= 2) {
String s = "00" + i;
System.out.println(s.substring(Math.min(2, s.length() - 2), s.length() - 2) + "." + s.substring(s.length() - 2));
}
Otherwise the DecimalFormat is the better solution. (the StringBuilder variant above won't work with small numbers (<100)
I think a simpler and more elegant solution to insert a String in a certain position would be this one-liner:
target.replaceAll("^(.{" + position + "})", "$1" + insert);
For example, to insert a missing : into a time String:
"-0300".replaceAll("^(.{3})", "$1:");
What it does is, matches position characters from the beginning of the string, groups that, and replaces the group with itself ($1) followed by the insert string. Mind the replaceAll, even though there's always one occurrence, because the first parameter must be a regex.
Of course it does not have the same performance as the StringBuilder solution, but I believe the succinctness and elegance as a simple and easier to read one-liner (compared to a huge method) is sufficient for making it the preferred solution in most non performance-critical use-cases.
Note I'm solving the generic problem in the title for documentation reasons, of course if you are dealing with decimal numbers you should use the domain-specific solutions already proposed.
There are good answers here, but with Kotlin extensions addition we can do it even more simply:
val indexWhereInsertIsIntended = 2
val inputString = "2408"
val resultingString = inputString.toCharArray().toMutableList()
.also {
it.add(indexWhereInsertIsIntended, '/')
}.joinToString("")
Result = 24/08
This example shows a card expiry date, and slash (/) is intended at 2nd Index. So the resulting index in this case will have / at 2nd index.
If you want to replace and not add:
val indexWhereInsertIsIntended = 2
val inputString = "2408"
val resultingString = inputString.toCharArray()
.also {
it[indexWhereInsertIsIntended] = '/'
}.joinToString("")
Result = 24/0
public static void main(String[] args) {
char ch='m';
String str="Hello",k=String.valueOf(ch),b,c;
System.out.println(str);
int index=3;
b=str.substring(0,index-1 );
c=str.substring(index-1,str.length());
str=b+k+c;
}
// Create given String and make with size 30
String str = "Hello How Are You";
// Creating StringBuffer Object for right padding
StringBuffer stringBufferRightPad = new StringBuffer(str);
while (stringBufferRightPad.length() < 30) {
stringBufferRightPad.insert(stringBufferRightPad.length(), "*");
}
System.out.println("after Left padding : " + stringBufferRightPad);
System.out.println("after Left padding : " + stringBufferRightPad.toString());
// Creating StringBuffer Object for right padding
StringBuffer stringBufferLeftPad = new StringBuffer(str);
while (stringBufferLeftPad.length() < 30) {
stringBufferLeftPad.insert(0, "*");
}
System.out.println("after Left padding : " + stringBufferLeftPad);
System.out.println("after Left padding : " + stringBufferLeftPad.toString());
Try this :
public String ConvertMessage(String content_sendout){
//use unicode (004E00650077) need to change to hex (&#x004E&#x;0065&#x;0077;) first ;
String resultcontent_sendout = "";
int i = 4;
int lengthwelcomemsg = content_sendout.length()/i;
for(int nadd=0;nadd<lengthwelcomemsg;nadd++){
if(nadd == 0){
resultcontent_sendout = "&#x"+content_sendout.substring(nadd*i, (nadd*i)+i) + ";&#x";
}else if(nadd == lengthwelcomemsg-1){
resultcontent_sendout += content_sendout.substring(nadd*i, (nadd*i)+i) + ";";
}else{
resultcontent_sendout += content_sendout.substring(nadd*i, (nadd*i)+i) + ";&#x";
}
}
return resultcontent_sendout;
}

Why does my toString method return 0?

Why does my toString method return 0? I have to concatenate an randomly generated integer onto a String and when I print the result it is always 0. What should I do?
class Cozi:
public String toString(){
String concat="";
Clienti ob = new Clienti();
for(int i=1;i <= Clienti.getNrClienti();i++){
concat = " <" + ob.getRandomInt2() + ">";
System.out.print(concat);
}
return concat;
}
class Clienti:
public int serviceTime(){
System.out.print("\n");
Random randomServ = new Random();
for (int idx = 1; idx <= nrClienti; ++idx){
randomInt2 = randomServ.nextInt(maxServ);
System.out.println("Generated : " + randomInt2);
}
return randomInt2;
}
I have also the methods get and set randomInt2.
I foud out why I was getting only 0. Because randomInt2 was declared int in class Clienti, instead of private static int. Now the problem I got is that my concat object gets only the last value for randomInt2. Any suggestions?
If you have an empty String "" as a return value, then it means you do not enter the for loop. Check if the condition i <= Clienti.getNrClienti() is met for any i.
And there is a bug in the for loop, you have to modify:
concat=" <"+ob.getRandomInt2()+">";
By
concat += " <"+ob.getRandomInt2()+">";
Note: when you want to concatenate Strings you can use StringBuilder which is more performant.
String s = "a";
s = "b";
System.out.println(s); // b
You want to concat if I got that right:
String s = "a";
s = s + "b";
System.out.println(s); // ab

charAt error "char cannot be converted to string"

I am trying to use the following code so that given a string, give the length of the longest contiguous subsequence of the same character. I am getting the error "incompatible types: char cannot be converted to java.lang.String". I have commented where the error is being found below.
public class Test {
public int longestRep(String str)
{
int currLen = 1;
String currLet = "";
String maxLet = "";
int maxCount = 0;
int currPos = 0;
int strLen = str.length();
for(currPos = 0; currPos < strLen; currPos++)
{
currLet = str.charAt(currPos); //error is on this line
if(currLet = str.charAt(currPos+1))
{
currLen++;
}
else
{
if(currLen > maxLen)
{
maxLen = currLen;
maxLet = currLet;
currLen = 1;
}
}
}
}
public static void main(String args[])
{
longestRep("AaaaMmm");
}
}
String.charAt(int) returns a character. But currLet is of type String, so you can't assign a character. Use currLet = Character.toString(str.charAt(currPos)); instead.
As the compiler said, you can't convert a char to a String. If you have a char and you really want to convert it to a String of length 1, this will work:
String s = String.valueOf(c);
or
String s = Character.toString(c);
However, if the character you're working with was obtained by charAt, another solution is to get rid of charAt and use substring to return a string of length 1:
currLet = str.substring(currPos, currPos + 1);
Easy way to convert Char to String
Add an empty String to the start of expression, because adding char and String results into String.
Convert one char "" + 'a'
Convert multiple chars "" + 'a' + 'b'
Converting multiple chars works because "" + 'a' is evaluated first.
If the "" were at the end instead you would get "195"
Remember that Java language guarantees (Java Language Specification, Java SE 7 Edition, section 15.12.4.2) that all arguments are evaluated from left to right (unlike some other languages, where the order of evaluation is undefined)
currLet = str.charAt(currPos); A String value can't be assigned to a char, they are different types, apples and oranges
if (currLet = str.charAt(currPos + 1)) { is actually an assignment (make currLet equal to the value of str.charAt(currPos + 1))
if (currLen > maxLen) { - maxLen is undefined
You never return anything from the method...
Try changing:
String currLet = ""; to something more like char currLet = '\0'; and String maxLet = ""; to char maxLet = '\0';
if (currLet = str.charAt(currPos + 1)) { to something like if (currLet == str.charAt(currPos + 1)) {
Add int maxLen = 0 to your variable declerations (may be under int maxCount = 0)
Now, based on your example code, public int longestRep(String str) { will need to be public static int longestRep(String str) { in order for you to call from you main method...

How can I find the sum of two numbers which are in String variables?

In this code fragment, I can't sum a and b:
String a = "10";
String b = "20";
JOptionPane.showMessageDialog(null,a+b);
Since a and b are defined as String, this code will concatenate the strings and output 10+20=1020.
How can I get it to instead sum a and b and output 10+20=30?
Java provides parse methods for Primitive Types. So depending on your input you can use Integer.parseInt, Double.parseDouble or others.
String result;
try{
int value = Integer.parseInt(a)+Integer.parseInt(b);
result = String. valueOf(value) ;
}catch(NumberFormatException ex){
//either a or b is not a number
result = "Invalid input";
}
JOptionPane.showMessageDialog(null,result);
Because you want to concat Strings they won't add up. You have to parse them to an Integer which works like:
Integer.parseInt(a) + Integer.parseInt(b)
To sum this up + concats Strings and doesn't add them up.
use BigInteger class to perform largely in length string addition operation.
BigInteger big = new BigInteger("77777777777777777777888888888888888888888888888856666666666666666666666666666666");
BigInteger big1 = new BigInteger("99999999999999995455555555555555556");
BigInteger big3 = big.add(big1);
try: Integer.parseInt(a)+Integer.parseInt(b)
String a= txtnum1.getText();
String b= txtnum2.getText();
JOptionPane.showMessageDialog(null,Integer.parseInt(a)+Integer.parseInt(b));
public void actionPerformed(ActionEvent arg0)
{
String a= txtnum1.getText();
String b= txtnum2.getText();
String result = "";
try{
int value = Integer.parseInt(a)+Integer.parseInt(b);
result = ""+value;
}catch(NumberFormatException ex){
result = "Invalid input";
}
JOptionPane.showMessageDialog(null,result);
}
it is work
Integer wrapper class has constructor which takes String parameter representing numbers.
String a= txtnum1.getText();//a="100"
String b= txtnum2.getText();//b="200"
Integer result;
int result_1;
String result_2;
try{
result = new Integer(a) + new Integer(b); // here variables a and b are Strings representing numbers. If not numbers, then new Integer(String) will throw number format exception.
int result_1=result.intValue();//convert to primitive datatype int if required.
result_2 = ""+result; //or result_2 = ""+result_1; both will work to convert in String format
}catch(NumberFormatException ex){
//if either a or b are Strings not representing numbers
result_2 = "Invalid input";
}
We can change string to BigInteger and then sum its values.
import java.util.*;
import java.math.*;
class stack
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
String aa=s.next();
String bb=s.next();
BigInteger a=new BigInteger(aa);
BigInteger b=new BigInteger(bb);
System.out.println(a.add(b));
}
}
Since + is used to concat strings, you can't use it to add two strings containing number. But subtraction works perfectly fine with such strings. Hence, you can use this basic mathematical concept to make that possible:
a-(-b)
Integer.parseInt() is used to convert String to Integer.In order to perform sum of two strings first strings need to be converted to Integers and then need to perform sum otherwise it just concatenates two strings instead of performing sum.
String a = "10";
String b = "20";
JOptionPane.showMessageDialog(null,Integer.parseInt(a)+Integer.parseInt(b));
public String addTwoNumbers(final String n1, final String n2) {
StringBuilder sb = new StringBuilder();
int carry =0;
byte[] nb1; byte[] nb2;
if (n1.length() > n2.length()){
nb1 = n1.getBytes();
nb2 = n2.getBytes();
} else {
nb2 = n1.getBytes();
nb1 = n2.getBytes();
}
int maxLen=n1.length()>=n2.length()?n1.length():n2.length();
for (int i = 1; i <= maxLen ; i++) {
int a = nb1.length-i >= 0 ? nb1[nb1.length-i] - 48 : 0;
int b = nb2.length-i >= 0 ? nb2[nb2.length-i] - 48 : 0;
int result = a + b + carry;
if (result >= 10){
carry = 1;
result = result-10;
} else {
carry = 0;
}
sb.insert(0, result);
}
if(carry>0){
sb.insert(0, carry);
}
return sb.toString();
}

Categories

Resources