rust


How to convert char to integer so that '1' becomes 1?


I am trying to find sum of all the digits of a given number, like 134 gives 8.
My plan is to iterate over the number by converting it into a string using .to_string() and then use .chars() to iterate over the number. Then I want to convert every char in the iteration into an integer and add into a variable. I want to get the final value of this variable.
I tried using the code below to convert a char into an integer (Playground):
fn main() {
let x = "123";
for y in x.chars() {
let z = y.parse::<i32>().unwrap();
println!("{}", z + 1);
}
}
But it results in this error:
error: no method named `parse` found for type `char` in the current scope
--> <anon>:4:19
|
4 | let z = y.parse::<i32>().unwrap();
| ^^^^^
How can I convert a char into an integer?
The below code does exactly what I want to do (Playground):
fn main() {
let mut sum = 0;
let x = 123;
let x = x.to_string();
for y in x.chars() {
// converting `y` to string and then to integer
let z = (y.to_string()).parse::<i32>().unwrap();
// incrementing `sum` by `z`
sum += z;
}
println!("{}", sum);
}
but first I have to convert char into a string and then into an integer to increment sum by z. Is there a way to directly convert char into integer?
The method you need is char::to_digit. It converts char to a number it represents in the given radix.
You can also use Iterator::sum to calculate sum of a sequence conveniently:
fn main() {
const RADIX: u32 = 10;
let x = "134";
println!("{}", x.chars().map(|c| c.to_digit(RADIX).unwrap()).sum::<u32>());
}
my_char as u32 - '0' as u32
Now, there's a lot more to unpack about this answer.
It works because the ASCII (and thus UTF-8) encodings have the Arabic numerals 0-9 ordered in ascending order. You can get the scalar values and subtract them.
However, what should it do for values outside this range? What happens if you provide 'p'? It returns 64. What about '.'? This will panic. And '♥' will return 9781.
Strings are not just bags of bytes. They are UTF-8 encoded and you cannot just ignore that fact. Every char can hold any Unicode scalar value.
That's why strings are the wrong abstraction for the problem.
From an efficiency perspective, allocating a string seems inefficient. Rosetta Code has an example of using an iterator which only does numeric operations:
struct DigitIter(usize, usize);
impl Iterator for DigitIter {
type Item = usize;
fn next(&mut self) -> Option<Self::Item> {
if self.0 == 0 {
None
} else {
let ret = self.0 % self.1;
self.0 /= self.1;
Some(ret)
}
}
}
fn main() {
println!("{}", DigitIter(1234, 10).sum::<usize>());
}
The method parse() is defined on str, not on char. A char is a Unicode codepoint, which is 32 bits wide. If you cast it to an integer, using u32 is preferred over i32.
You can cast it via as or into():
let a = '♥' as u32;
let b: u32 = '♥'.into();
Another way is to iterate over the characters of your string and convert and add them using fold.
fn sum_of_string(s: &str) -> u32 {
s.chars().fold(0, |acc, c| c.to_digit(10).unwrap_or(0) + acc)
}
fn main() {
let x = "123";
println!("{}", sum_of_string(x));
}

Related Links

Acessing data from a global struct, gives error “borrowed value does not live long enough”
captured variable does not outlive the enclosing closure [duplicate]
PI constant is ambiguous
Calling an impl method from another impl method
compilation of openssl-sys fails with `openssl/hmac.h: No such file or directory`
Indexing a String
Importing mio::tcp::TcpStream but get std::net::tcp::TcpStream
It is possible to always have Cargo show warnings?
Copy files to the target directory after build
Is it ok to return in main?
Why is this trait/implementation incompatible - bound lifetime vs concrete lifetime
Cannot move out of `req` because it is borrowed
remove duplicates from vector of custom struct
error with % operator inside closure
How can I open a file with the standard text editor?
How to use multiple variables in routes with Nickel?

Categories

HOME
opengl
tomcat
angular-ui-grid
dotnetnuke
kendo-dropdown
message-queue
docker-cloud
malware
fogbugz
tibco
position
ag-grid
angular2-template
pyresttest
timber
tup
solution
powermock
squid
user-defined-types
gravity
http-authentication
animated-gif
function-points
tortoisemerge
plyr
sap-lumira
python-imageio
django-import-export
adapter
sparkle
premake
listjs
cloudera-quickstart-vm
unification
sspi
google-now
utf
resampling
oauth2-playground
grails3.2.0
classnotfoundexception
viewcontroller
word-cloud
wysihtml5
xcglogger
supertest
knockout-2.0
word-2007
nivo-slider
dblink
prefetch
maatwebsite-excel
ternary-operator
portal
fuzzer
tsqlt
qtcpsocket
declarative
groovyfx
fdt
vaadin4spring
gulp-uglify
taco
wikimedia-commons
myfaces
boost-proto
asp.net-web-api-helppages
blank-line
screen-orientation
dbmigrate
whitespace-language
symja
datagridcomboboxcolumn
zend-mail
jquery-mobile-flipswitch
windows-taskbar
frontbase
libxml-js
objective-c-runtime
onconfigurationchanged
yuidoc
multidrop-bus
zend-server-ce
will-paginate
motodev-studio
tablet-pc
grails-validation
django-pagination
channelfactory
downgrade
android-2.1-eclair
projectpier

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App