How to extract only alphabets from mixed string

조회 수: 22 (최근 30일)
Mekala balaji
Mekala balaji 2016년 3월 26일
편집: Ced 2016년 3월 26일
Hi,
I have a mixed string as below:
string=BA9K90L
And I only want to extract alphabets i.e., BAKL. Kindly some one help how can we do this.
Many thanks in advance,

채택된 답변

Stephen23
Stephen23 2016년 3월 26일
This is easy using the inbuilt isstrprop function:
>> S = 'BA9K90L';
>> S(isstrprop(S,'alpha'))
ans =
BAKL

추가 답변 (1개)

Ced
Ced 2016년 3월 26일
편집: Ced 2016년 3월 26일
Hi
You can use fancy functions like regexp or so, but this is my suggestion:
str = 'BA9K90L';
% pick out letters only (using ASCII value)
str = str(double(str) > 64)
Done! :)
Cheers
EDIT: This does not work if you have more than alphanumeric strings, see Stephen's answer for a complete check.
  댓글 수: 5
Guillaume
Guillaume 2016년 3월 26일
I totally agree with Stephen. Correct and obvious code trumps fast code. While comparing to 'A' (and that would have been clearer than comparing to 64) works in the toy example provided, it certainly is not robust.
There are tons of characters (>120,000 in the unicode standard) above 64 that may or may not be alphabetic. isstrprop at least attempts to do the right thing and takes into account the current locale.
Ced
Ced 2016년 3월 26일
편집: Ced 2016년 3월 26일
@Guillaume:
Of course. I admit that I understood the question as "if I have a string with letters and numbers, how to I extract the letters", as this was given in the example. I have no problem admitting the correctness of his solution, and it was good to point out the limitation. That being said, I see this forum as a place where people share ideas and solutions, and not one of industrial competition. Even Dr. Siva's answer, while being unnecessarily long, is a contribution. It's up to the OP to decide which answer suits their need.
Anyway, that is irrelevant for the topic at hand.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by