Как перевести integer в string

Java Преобразует целое число в строку

Вступление

Преобразование целого числа в строку

Строка.Значение()

Метод valueOf() является статическим методом класса String, который возвращает строковое представление указанного типа.

Здесь разрешено много типов:

Запуск этого фрагмента кода приведет к:

Это имеет смысл, поскольку оба этих метода возвращают новую строку. Метод equals() возвращает true, потому что их значение одинаково, тогда как == возвращает false, поскольку их ссылочные переменные не указывают на один и тот же объект в памяти.

Из-за этого рекомендуется использовать метод valueOf() как для преобразования строк, так и целых чисел.

Целое число.toString()

Этот подход использует один из наиболее распространенных методов Java – toString() общий для всех объектов.

Этот метод имеет множество применений и требует подробного объяснения. Если вы хотите прочитать об этом больше, у нас уже есть отличная статья, посвященная этому!

В этом случае метод возвращает строковый объект, представляющий указанное значение int. Аргумент преобразуется в десятичное представление со знаком и возвращается в виде строки:

Запуск этого фрагмента кода приведет к:

Строка.формат()

Возвращает строку, отформатированную в соответствии со спецификатором формата и следующими аргументами. Хотя целью этого метода является не совсем преобразование, а скорее форматирование строки, его также можно использовать для преобразования.

Существует довольно много спецификаторов на выбор:

В этом уроке мы сосредоточимся на %d :

Запуск этого фрагмента кода приведет к:

Git Essentials

Ознакомьтесь с этим практическим руководством по изучению Git, содержащим лучшие практики и принятые в отрасли стандарты. Прекратите гуглить команды Git и на самом деле изучите это!

Строковый конструктор и строковый буферизатор

Оба StringBuffer и StringBuilder являются классами, используемыми для объединения нескольких значений в одну строку.

StringBuffer потокобезопасен, но медленнее, тогда как StringBuilder не потокобезопасен, но быстрее.

Запуск этого фрагмента кода приведет к:

Вывод

Мы рассмотрели одну из фундаментальных тем Java и общих проблем, с которыми сталкиваются разработчики, – преобразование int или целого числа в строку с помощью инструментов, поставляемых с JDK.

Источник

Java конвертировать int в string

Java: преобразование строки в число и наоборот в OTUS, только интересные посты!

Преобразование с использованием Integer.toString(int)

Класс Integer имеет статический метод, который возвращает объект String, представляющий параметр int, указанный в функции Integer.toString(int). Этот подход, в отличие от других, может возвращать исключение NullPointerException.

Синтаксис

Есть два разных выражения для метода Integer.toString():

public static String toString(int i)public static String toString(int i, int radix)

Параметры

Параметры этого метода:

Значение radix является необязательным параметром, и если оно не установлено, для десятичной базовой системы значением по умолчанию является 10.

Возвращаемое значение

Возвращаемое значение для обоих выражений – строка Java, представляющая целочисленный аргумент «i». Если используется параметр radix, возвращаемая строка определяется соответствующим основанием.

Пример

Вывод

Обсуждение

Когда вы изучите пример выше, вы увидите, что метод Integer.parseInt (s.trim ()) используется для превращения строки s в целое число i, и происходит это в следующей строке кода:int i = Integer.parseInt (s.trim ())Но иногда перевести строку в число просто так не получится. В нашем примере такая строка — имя fred. Можно говорить о кодах, в которых буквы записываются в компьютере, но, формально говоря, fred никакое не число, и лучше его оставить строкой. Наша программа организована так, что при попытке преобразования «фреда» в число процесс Integer parseInt вызовет исключение NumberFormatException, которое вы должны обрабатывать в блоке try / catch.В этом случае вам не обязательно использовать метод trim () класса String, но в реальном программировании вы должны его использовать. Так что мы его вам продемонстрировали.Раз уж поднялась такая тема, вот вам несколько «хинтов» по теме о классах String и Integer:

Автор ответа: Элис Уотсон

Описание

Метод toString() — используется в Java для получения строкового объекта, представляющего значение числового объекта, другими словами — преобразует число в строку.

Если метод принимает в качестве аргумента простой тип данных, то возвращается строковый объект, представляющий значение простого типа данных.

Если метод toString() в Java принимает два аргумента, то будет возвращено строковое представление первого аргумента в системе счисления по целочисленному основанию, указанному вторым аргументом.

Синтаксис

Все вариант метода приведены ниже:

Перевод с использованием String.valueOf(int)

String.valueOf() – это статический служебный метод класса String, который может преобразовывать большинство примитивных типов данных в их представление String. Включает целые числа. Этот подход считается лучшей практикой благодаря своей простоте.

Синтаксис

Это выражается как:

public static String valueOf(int i)

Параметр

i: целое число, которое должно быть преобразовано.

Возвращаемое значение

Этот метод возвращает строковое представление аргумента int.

Источник

How do I convert from int to String?

I’m working on a project where all conversions from int to String are done like this:

I’m not familiar with Java.

Is this usual practice or is something wrong, as I suppose?

Как перевести integer в string

20 Answers 20

The concatenation will work, but it is unconventional and could be a bad smell as it suggests the author doesn’t know about the two methods above (what else might they not know?).

Java has special support for the + operator when used with strings (see the documentation) which translates the code you posted into:

Initialise the StringBuilder:

Append the empty string:

Append the integer:

Extract the final string:

There’s a proposal and ongoing work to change this behaviour, targetted for JDK 9.

Как перевести integer в string

It’s acceptable, but I’ve never written anything like that. I’d prefer this:

It’s not a good way.

When doing conversion from int to string, this should be used:

Как перевести integer в string

I don’t want to append an integer to an (empty) string. I want to convert an integer to string:

Or, not my prefered, but still better than concatenation, get a string representation of an object (integer):

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 + i;

Как перевести integer в string

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.

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.

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.

Как перевести integer в string

The other way I am aware of is from the Integer class:

A concrete example (though I wouldn’t think you need any):

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.

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.

Как перевести integer в string

20ns longer than the other two methods (which both take

50ns per conversion), so the differences you saw in the order of ms are probably due to random error (scheduling, interrupts, etc).

There are various ways of converting to Strings:

Как перевести integer в string

It depends on how you want to use your String. This can help:

Как перевести integer в string

Как перевести integer в string

There are many way to convert an integer to a string:

Как перевести integer в string

Как перевести integer в string

There are three ways of converting to Strings

Как перевести integer в string

Как перевести integer в string

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.

Both of the ways are correct.

Как перевести integer в string

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.

Источник

Самый простой способ конвертировать int в string в C++

какой самый простой способ конвертировать из int в эквиваленте string В C++. Я знаю два метода. Есть ли более простой способ?

25 ответов

поэтому это самый короткий путь, который я могу придумать. Вы даже можете опустить имя типа, используя auto ключевые слова:

Примечание:[строка.преобразования] (21.5 на n3242)

взяв в руки дискуссии с @В. oddou пару лет спустя, в C++17, наконец, доставлены способ сделать изначально макрос-тип-агностик Решение (ниже) без проходя через макро-уродство.

оригинальный ответ:

использование так же просто, как могло бы быть:

выше C++98 совместим (если вы не можете использовать C++11 std::to_string ), и не нуждается в каких-либо сторонних включает (если вы не можете использовать Boost lexical_cast<> ); оба эти другие решения имеют лучшую производительность.

обычно я использую следующий метод:

одна из тонкостей этого заключается в том, что он также поддерживает другие слепки (например, в противоположном направлении работает так же хорошо).

начиная с C++11, есть std::to_string функция перегружена для целочисленные типы, поэтому вы можете использовать код типа:

стандарт определяет их как эквивалентные выполнению преобразования с помощью sprintf (используя спецификатор преобразования, который соответствует указанному типу объекта, например, %d на int ), в буфер достаточного размера, а затем создание std::string содержимое этого буфера.

Если у вас установлен Boost (который вы должны):

Источник

How to convert int to String in Java

How to convert int to string in Java

Convert by adding an empty string.

Here is an example:

The output is:

Java convert int to string using Integer.toString(int)

Object class is a root class in Java. That means every Java class is directly or indirectly inherited from the Object class and all Object class methods are available for all Java classes.

Object has a special method toString() to represent any object as a string. So, every Java class inherits this method as well. However the good idea is to override this method in your own classes to have an appropriate result.

The Integer class’ toString() method returns a String object representing the specified int or Integer parameter.

The method converts argument i and returns it as a string instance. If the number is negative, the sign will be kept.

You may use the toString method to convert an Integer (wrapper type) as well.

The result is:

You may use special Integer.toString method toString(int i, int base) that returns a string representation of the number i with the base base and than to String. For example

Here is an example:

The output is a String binary representation of decimal number 255:

Convert int to String using String.valueOf(int)

Method String.valueOf(int) returns the string representation of the int argument.

The syntax of the method is:

Here is an example of Java convert int to String using String.valueOf(int) :

You may do the same with an Integer (wrapper type of int):

The output will be:

Convert using DecimalFormat

Convert using String.format()

String.format() is one more way to convert an Integer to String Object.

Syntax

Example

How to convert String to int in Java

Java string to int using Integer.parseInt(String)

parseInt is a static method of the Integer class that returns an integer object representing the specified String parameter.

Syntax:

Where str is a String you need to convert and radix is a base of the parsed number

Converting String to Integer, Java example using parseInt()

Here we’ve got 111 in the first variant and 7 for the second. 7 is a decimal form of binary 111.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *