sum function usage for string

5 ビュー (過去 30 日間)
Xuande Zhang
Xuande Zhang 2020 年 9 月 14 日
コメント済み: Star Strider 2020 年 9 月 14 日
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 Center および File ExchangeCharacters and Strings についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by