int에서 String으로 어떻게 변환합니까?
나는 모든 변환 프로젝트에서 일하고 있어요 int
으로는 String
다음과 같이 수행됩니다 :
int i = 5;
String strI = "" + i;
Java에 익숙하지 않습니다. 이것이 일반적인 관행입니까 아니면 내가 생각하는 것처럼 잘못된 것입니까?
일반적인 방법은 Integer.toString(i)
또는 String.valueOf(i)
입니다.
연결은 작동하지만, 이것은 틀에 얽매이지 않으며 저자가 위의 두 가지 방법에 대해 알지 못함을 시사하므로 악취가 날 수 있습니다 (그 밖에 모르는 것은 무엇입니까?).
Java는 게시 한 코드를 다음과 같이 변환하는 문자열 ( 문서 참조)과 함께 사용할 때 + 연산자를 특별히 지원합니다 .
StringBuilder sb = new StringBuilder();
sb.append("");
sb.append(i);
String strI = sb.toString();
컴파일 타임에. 그것은 약간 덜 효율적인 (의 sb.append()
호출 끝나는 Integer.getChars()
것 인, Integer.toString()
어쨌든 했을),하지만 작동합니다.
Grodriguez의 의견에 답하기 위해 : ** 아니요, 컴파일러 는 이 경우 빈 문자열을 최적화 하지 않습니다 .
simon@lucifer:~$ cat TestClass.java
public class TestClass {
public static void main(String[] args) {
int i = 5;
String strI = "" + i;
}
}
simon@lucifer:~$ javac TestClass.java && javap -c TestClass
Compiled from "TestClass.java"
public class TestClass extends java.lang.Object{
public TestClass();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: iconst_5
1: istore_1
StringBuilder를 초기화합니다.
2: new #2; //class java/lang/StringBuilder
5: dup
6: invokespecial #3; //Method java/lang/StringBuilder."<init>":()V
빈 문자열을 추가합니다.
9: ldc #4; //String
11: invokevirtual #5; //Method java/lang/StringBuilder.append:
(Ljava/lang/String;)Ljava/lang/StringBuilder;
정수 추가 :
14: iload_1
15: invokevirtual #6; //Method java/lang/StringBuilder.append:
(I)Ljava/lang/StringBuilder;
최종 문자열을 추출합니다.
18: invokevirtual #7; //Method java/lang/StringBuilder.toString:
()Ljava/lang/String;
21: astore_2
22: return
}
거기에 제안 JDK 9 타겟으로이 동작을 변경하고 지속적인 작업.
받아 들일 수 있지만 그런 글을 쓴 적이 없습니다. 나는 이것을 선호한다 :
String strI = Integer.toString(i);
좋은 방법이 아닙니다.
int에서 문자열로 변환 할 때 다음을 사용해야합니다.
int i = 5;
String strI = String.valueOf(i);
최적화 뿐만이 아닙니다 1 . 나는 싫어
"" + i
내가 정말로하고 싶은 것을 표현하지 않기 때문이다 2 .
(빈) 문자열에 정수를 추가하고 싶지 않습니다. 정수를 문자열로 변환하고 싶습니다.
Integer.toString(i)
Or, not my prefered, but still better than concatenation, get a string representation of an object (integer):
String.valueOf(i)
1. For code that is called very often, like in loops, optimization sure is also a point for not using concatenation.
2. this is not valid for use of real concatenation like in System.out.println("Index: " + i);
or String id = "ID" + i;
A lot of introductory University courses seem to teach this style, for two reasons (in my experience):
It doesn’t require understanding of classes or methods. Usually, this is taught way before the word “class” is ever mentioned – nor even method calls. So using something like
String.valueOf(…)
would confuse students.It is an illustration of “operator overloading” – in fact, this was sold to us as the idiomatic overloaded operator (small wonder here, since Java doesn’t allow custom operator overloading).
So it may either be born out of didactic necessity (although I’d argue that this is just bad teaching) or be used to illustrate a principle that’s otherwise quite hard to demonstrate in Java.
The expression
"" + i
leads to string conversion of i
at runtime. The overall type of the expression is String
. i
is first converted to an Integer
object (new Integer(i)
), then String.valueOf(Object obj)
is called. So it is equivalent to
"" + String.valueOf(new Integer(i));
Obviously, this is slightly less performant than just calling String.valueOf(new Integer(i))
which will produce the very same result.
The advantage of ""+i
is that typing is easier/faster and some people might think, that it's easier to read. It is not a code smell as it does not indicate any deeper problem.
(Reference: JLS 15.8.1)
Personally, I don't see anything bad in this code.
It's pretty useful when you want to log an int value, and the logger just accepts a string. I would say such a conversion is convenient when you need to call a method accepting a String, but you have an int value.
As for the choice between Integer.toString
or String.valueOf
, it's all a matter of taste.
...And internally, the String.valueOf
calls the Integer.toString
method by the way. :)
The other way I am aware of is from the Integer
class:
Integer.toString(int n);
Integer.toString(int n, int radix);
A concrete example (though I wouldn't think you need any):
String five = Integer.toString(5); // returns "5"
It also works for other primitive types, for instance Double.toString
.
This technique was taught in an undergraduate level introduction-to-Java class I took over a decade ago. However, I should note that, IIRC, we hadn't yet gotten to the String and Integer class methods.
The technique is simple and quick to type. If all I'm doing is printing something, I'll use it (for example, System.out.println("" + i);
. However, I think it's not the best way to do a conversion, as it takes a second of thought to realize what's going on when it's being used this way. Also, if performance is a concern, it seems slower (more below, as well as in other answers).
Personally, I prefer Integer.toString(), as it is obvious what's happening. String.valueOf() would be my second choice, as it seems to be confusing (witness the comments after darioo's answer).
Just for grins :) I wrote up classes to test the three techniques: "" + i, Integer.toString, and String.ValueOf. Each test just converted the ints from 1 to 10000 to Strings. I then ran each through the Linux time command five times. Integer.toString() was slightly faster than String.valueOf() once, they tied three times, and String.valueOf() was faster once; however, the difference was never more than a couple of milliseconds.
The "" + i technique was slower than both on every test except one, when it was 1 millisecond faster than Integer.toString() and 1 millisecond slower than String.valueOf() (obviously on the same test where String.valueOf() was faster than Integer.toString()). While it was usually only a couple milliseconds slower, there was one test where it was about 50 milliseconds slower. YMMV.
There are various ways of converting to Strings:
StringBuilder string = string.append(i).toString();
String string = String.valueOf(i);
String string = Integer.toString(i);
It depends on how you want to use your String. This can help:
String total = Integer.toString(123) + Double.toString(456.789);
String strI = String.valueOf(i);
String string = Integer.toString(i);
Both of the ways are correct.
There are many way to convert an integer to a string:
1)
Integer.toString(10);
2)
String hundred = String.valueOf(100); // You can pass an int constant
int ten = 10;
String ten = String.valueOf(ten)
3)
String thousand = "" + 1000; // String concatenation
4)
String million = String.format("%d", 1000000)
There are three ways of converting to Strings
String string = "" + i;
String string = String.valueOf(i);
String string = Integer.toString(i);
Mostly ditto on SimonJ. I really dislike the ""+i idiom. If you say String.valueOf(i), Java converts the integer to a string and returns the result. If you say ""+i, Java creates a StringBuilder object, appends an empty string to it, converts the integer to a string, appends this to the StringBuilder, then converts the StringBuilder to a String. That's a lot of extra steps. I suppose if you do it once in a big program, it's no big deal. But if you're doing this all the time, you're making the computer do a bunch of extra work and creating all these extra objects that then have to be cleaned up. I don't want to get fanatic about micro-optimization, but I don't want to be pointlessly wasteful either.
Using "" + i is the shortest and simplest way to convert a number to a string. It is not the most efficient, but it is the clearest IMHO and that is usually more important. The simpler the code, the less likely you are to make a mistake.
Personally I think that "" + i does look as the original question poster states "smelly". I have used a lot of OO languages besides Java. If that syntax was intended to be appropriate then Java would just interpret the i alone without needing the "" as desired to be converted to a string and do it since the destination type is unambiguous and only a single value would be being supplied on the right. The other seems like a 'trick" to fool the compiler, bad mojo when different versions of Javac made by other manufacturers or from other platforms are considered if the code ever needs to be ported. Heck for my money it should like many other OOL's just take a Typecast: (String) i. winks
Given my way of learning and for ease of understanding such a construct when reading others code quickly I vote for the Integer.toString(i) method. Forgetting a ns or two in how Java implements things in the background vs. String.valueOf(i) this method feels right to me and says exactly what is happening: I have and Integer and I wish it converted to a String.
A good point made a couple times is perhaps just using StringBuilder up front is a good answer to building Strings mixed of text and ints or other objects since thats what will be used in the background anyways right?
Just my two cents thrown into the already well paid kitty of the answers to the Mans question... smiles
EDIT TO MY OWN ANSWER AFTER SOME REFLECTION:
Ok, Ok, I was thinking on this some more and String.valueOf(i) is also perfectly good as well it says: I want a String that represents the value of an Integer. lol, English is by far more difficult to parse then Java! But, I leave the rest of my answer/comment... I was always taught to use the lowest level of a method/function chain if possible and still maintains readablity so if String.valueOf calls Integer.toString then Why use a whole orange if your just gonna peel it anyways, Hmmm?
To clarify my comment about StringBuilder, I build a lot of strings with combos of mostly literal text and int's and they wind up being long and ugly with calls to the above mentioned routines imbedded between the +'s, so seems to me if those become SB objects anyways and the append method has overloads it might be cleaner to just go ahead and use it... So I guess I am up to 5 cents on this one now, eh? lol...
use Integer.toString(tmpInt).trim();
Try simple typecasting
char c = (char) i;
참고URL : https://stackoverflow.com/questions/4105331/how-do-i-convert-from-int-to-string
'Development Tip' 카테고리의 다른 글
MongoDB 대 Cassandra (0) | 2020.09.29 |
---|---|
Vim 녹음이란 무엇이며 어떻게 비활성화 할 수 있습니까? (0) | 2020.09.29 |
각도 HTML 바인딩 (0) | 2020.09.29 |
입력 필드에서 속성을 읽을 때 HTML 인코딩이 손실 됨 (0) | 2020.09.29 |
++로 증가하는 파이썬 정수 (0) | 2020.09.29 |