sum function usage for string

10 次查看(过去 30 天)
Hello all,
I was working on an entry-level question "Number of 1s in a binary string", my answer was converting the number to string and use strfind function '1'.
Saw a very clean answer , I don't quite understand this. If x is a string, what can we get x-'0'
y = sum(x-'0')

采纳的回答

Star Strider
Star Strider 2020-9-14
Subtracting ASCII 0 from an ASCII string converts the string to numeric values.
There is some controversy as to that being ‘correct’, however it definitely does work! (It takes advantage of the fact that everything in a computer is stored as numeric representations.)
  2 个评论
Xuande Zhang
Xuande Zhang 2020-9-14
Thanks!
I am still digesting this, it's kind of tricky to use this I think.
Star Strider
Star Strider 2020-9-14
As always, my pleasure!
As I mentioned, it is a bit controversial.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by