int i = Integer.parseInt(s1, 10); float f = Float.parseFloat(s2); double d = Double.parseDouble(s3);
数字转字符串
C++中如何把数字转换为字符串
用sprintf函数
用ostreamstring对象
用to_string函数
用itoa函数
用sprintf函数
1 2 3 4 5 6
std::printf, std::fprintf, std::sprintf, std::snprintf Defined in header <cstdio> intprintf( constchar* format, ... ); (1) intfprintf( std::FILE* stream, constchar* format, ... ); (2) intsprintf( char* buffer, constchar* format, ... ); (3) intsnprintf( char* buffer, std::size_t buf_size, constchar* format, ... ); (4) (since C++11)
从给定位置加载数据,将它们转换为字符串等效项,并将结果写入各种接收器。 1) Writes the results to stdout. 2) Writes the results to a file stream stream. 3) Writes the results to a character string buffer. 4) Writes the results to a character string buffer. At most buf_size - 1 characters are written. The resulting character string will be terminated with a null character, unless buf_size is zero. If buf_size is zero, nothing is written and buffer may be a null pointer, however the return value (number of bytes that would be written) is still calculated and returned. If a call to sprintf or snprintf causes copying to take place between objects that overlap, the behavior is undefined.
Parameters stream - output file stream to write to buffer - pointer to a character string to write to buf_size - up to buf_size - 1 characters may be written, plus the null terminator format - pointer to a null-terminated multibyte string specifying how to interpret the data. The format string consists of ordinary multibyte characters (except %), which are copied unchanged into the output stream, and conversion specifications.
Return value 1-2) Number of characters written if successful or a negative value if an error occurred. 3) Number of characters written if successful (not including the terminating null character) or a negative value if an error occurred. 4) Number of characters that would have been written for a sufficiently large buffer if successful (not including the terminating null character), or a negative value if an error occurred. Thus, the (null-terminated) output has been completely written if and only if the returned value is nonnegative and less than buf_size.
#include<sstream> #include<iostream> intmain() { int n; std::istringstream in; // could also use in("1 2") in.str("1 2"); in >> n; std::cout << "after reading the first int from \"1 2\", the int is " << n << ", str() = \"" << in.str() << "\"\n"; std::ostringstreamout("1 2"); out << 3; std::cout << "after writing the int '3' to output stream \"1 2\"" << ", str() = \"" << out.str() << "\"\n"; std::ostringstreamate("1 2", std::ios_base::ate); ate << 3; std::cout << "after writing the int '3' to append stream \"1 2\"" << ", str() = \"" << ate.str() << "\"\n"; }
1 2 3 4
Output: after reading the first int from "1 2", the int is 1, str() = "1 2" after writing the int '3' to output stream "1 2", str() = "3 2" after writing the int '3' to append stream "1 2", str() = "1 23"
std::scanf, std::fscanf, std::sscanf Defined in header <cstdio> intscanf( constchar* format, ... ); (1) intfscanf( std::FILE* stream, constchar* format, ... ); (2) intsscanf( constchar* buffer, constchar* format, ... ); (3)
Reads data from the a variety of sources, interprets it according to format and stores the results into given locations. 1) Reads the data from stdin 2) Reads the data from file stream stream 3) Reads the data from null-terminated character string buffer Return value: Number of receiving arguments successfully assigned (which may be zero in case a matching failure occurred before the first receiving argument was assigned), or EOF if input failure occurs before the first receiving argument was assigned.
#include<iostream> #include<clocale> #include<cstdio> intmain() { int i, j; float x, y; char str1[10], str2[4]; wchar_t warr[2]; std::setlocale(LC_ALL, "en_US.utf8"); char input[] = u8"25 54.32E-1 Thompson 56789 0123 56ß水"; // parse as follows: // %d: an integer // %f: a floating-point value // %9s: a string of at most 9 non-whitespace characters // %2d: two-digit integer (digits 5 and 6) // %f: a floating-point value (digits 7, 8, 9) // %*d an integer which isn't stored anywhere // ' ': all consecutive whitespace // %3[0-9]: a string of at most 3 digits (digits 5 and 6) // %2lc: two wide characters, using multibyte to wide conversion int ret = std::sscanf(input, "%d%f%9s%2d%f%*d %3[0-9]%2lc", &i, &x, str1, &j, &y, str2, warr); std::cout << "Converted " << ret << " fields:\n" << "i = " << i << "\nx = " << x << '\n' << "str1 = " << str1 << "\nj = " << j << '\n' << "y = " << y << "\nstr2 = " << str2 << '\n' << std::hex << "warr[0] = U+" << warr[0] << " warr[1] = U+" << warr[1] << '\n'; } /* Output: Converted 7 fields: i = 25 x = 5.432 str1 = Thompson j = 56 y = 789 str2 = 56 warr[0] = U+df warr[1] = U+6c34 */
用istreamstring对象
1 2 3 4 5 6 7 8 9
std::istringstream in; // could also use in("1 2") in.str("1 2"); in >> n; std::cout << "after reading the first int from \"1 2\", the int is " << n << ", str() = \"" << in.str() << "\"\n"; /* Output: after reading the first int from "1 2", the int is 1, str() = "1 2" */
std::stoi, std::stol, std::stoll Defined in header <string> int stoi( const std::string& str, std::size_t* pos = 0, int base = 10 ); int stoi( const std::wstring& str, std::size_t* pos = 0, int base = 10 ); (1) (since C++11) long stol( const std::string& str, std::size_t* pos = 0, int base = 10 ); long stol( const std::wstring& str, std::size_t* pos = 0, int base = 10 ); (2) (since C++11) long long stoll( const std::string& str, std::size_t* pos = 0, int base = 10 ); long long stoll( const std::wstring& str, std::size_t* pos = 0, int base = 10 ); (3) (since C++11)
std::stoul, std::stoull Defined in header <string> unsigned long stoul( const std::string& str, std::size_t* pos = 0, int base = 10 ); unsigned long stoul( const std::wstring& str, std::size_t* pos = 0, int base = 10 ); (1) (since C++11) unsigned long long stoull( const std::string& str, std::size_t* pos = 0, int base = 10 ); unsigned long long stoull( const std::wstring& str, std::size_t* pos = 0, int base = 10 ); (2) (since C++11)
Parameters str - the string to convert pos - address of an integer to store the number of characters processed base - the number base Return value The string converted to the specified signed integer type. Exceptions std::invalid_argument if no conversion could be performed std::out_of_range if the converted value would fall out of the range of the result type or if the underlying function (std::strtol or std::strtoll) sets errno to ERANGE.
std::strtol, std::strtoll Defined in header <cstdlib> longstrtol( constchar *str, char **str_end, int base ); longlongstrtoll( constchar *str, char **str_end, int base ); (since C++11)
#include<iostream> #include<string> #include<cerrno> #include<cstdlib> intmain() { constchar* p = "111.11 -2.22 0X1.BC70A3D70A3D7P+6 1.18973e+4932zzz"; char* end; std::cout << "Parsing \"" << p << "\":\n"; for (double f = std::strtod(p, &end); p != end; f = std::strtod(p, &end)) { std::cout << "'" << std::string(p, end-p) << "' -> "; p = end; if (errno == ERANGE){ std::cout << "range error, got "; errno = 0; } std::cout << f << '\n'; } } /* Output: Parsing "111.11 -2.22 0X1.BC70A3D70A3D7P+6 1.18973e+4932zzz": '111.11' -> 111.11 ' -2.22' -> -2.22 ' 0X1.BC70A3D70A3D7P+6' -> 111.11 ' 1.18973e+4932' -> range error, got inf */
Java中如何把数字转换为字符串
函数原型:
1 2
publicstatic String toString(int i, int radix)
该函数是类Integer中的一个静态方法,该函数作用是把整数按某一进制转换成字符串并返回。具体的描述如下(摘自Java SE 8参考文档)。
Returns a string representation of the first argument in the radix specified by the second argument. If the radix is smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX, then the radix 10 is used instead.
If the first argument is negative, the first element of the result is the ASCII minus character ‘-‘ (‘\u002D’). If the first argument is not negative, no sign character appears in the result.
The remaining characters of the result represent the magnitude of the first argument. If the magnitude is zero, it is represented by a single zero character ‘0’ (‘\u0030’); otherwise, the first character of the representation of the magnitude will not be the zero character. The following ASCII characters are used as digits:
1
0123456789abcdefghijklmnopqrstuvwxyz
These are ‘\u0030’ through ‘\u0039’ and ‘\u0061’ through ‘\u007A’. If radix is N, then the first N of these characters are used as radix-N digits in the order shown. Thus, the digits for hexadecimal (radix 16) are 0123456789abcdef. If uppercase letters are desired, the String.toUpperCase() method may be called on the result: Integer.toString(n, 16).toUpperCase()
publicstaticintparseInt(String s, int radix) throws NumberFormatException
该函数是类Integer中的一个静态方法,该函数作用是把字符串按某一进制转换成整数并返回。具体的描述如下(摘自Java SE 8参考文档)。
Parses the string argument as a signed integer in the radix specified by the second argument. The characters in the string must all be digits of the specified radix (as determined by whether Character.digit(char, int) returns a nonnegative value), except that the first character may be an ASCII minus sign ‘-‘ (‘\u002D’) to indicate a negative value or an ASCII plus sign ‘+’ (‘\u002B’) to indicate a positive value. The resulting integer value is returned.
An exception of type NumberFormatException is thrown if any of the following situations occurs:
The first argument is null or is a string of length zero.
The radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX.
Any character of the string is not a digit of the specified radix, except that the first character may be a minus sign ‘-‘ (‘\u002D’) or plus sign ‘+’ (‘\u002B’) provided that the string is longer than length 1.
The value represented by the string is not a value of type int.