简体   繁体   English

如何将整数值转换为字符串?

[英]How to convert an integer value to string?

如何在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 看到它在线工作: 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. 这是手动将int转换为String值的方法。如果我做错了,任何人都会纠正我。

/**
 * @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();
}

There are many different type of wat to convert Integer value to string 有许多不同类型的wat将Integer值转换为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)
  Integer yourInt;
  yourInt = 3;
  String yourString = yourInt.toString();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM