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 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