so I have the following line of code:
hashtag=lower(input('Which hashtag would you like information on?','s'));
This prompts the user to input a hashtag, like say '#helloworld'. However, the program runs even without the user putting the hashtag. So it runs even if they only input "helloworld", which presents problems for me later on. How can I get the code to stop reading and present an error message if there is no hashtag symbol in the user's input? Apparently the # character means something in matlab as well which is causing me problems.
I have this so far but it seems not to work:
if k=(strfind(hashtag,'#')))
error('Please include the hashtag')
end

 채택된 답변

The Matlab Spot
The Matlab Spot 2013년 12월 3일

0 개 추천

using start anchor with regexp will ensure that you '#' as the first character of you input string.
hashtag=lower(input('Which hashtag would you like information on?','s'));
if(isempty(regexp(hashtag,'^#','once')))
error('Please include the hashtag')
end

댓글 수: 2

Johny
Johny 2013년 12월 3일
This answer is more robust than the one above, so best answer goes to you. I didn't know the ^ symbol did anything at all actually. I learned something!Thanks to both of you guys though.
Jos (10584)
Jos (10584) 2013년 12월 3일
using regexp for this problem is like killing a mosquito with a nuclear missile ...

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

추가 답변 (2개)

sixwwwwww
sixwwwwww 2013년 12월 3일

0 개 추천

Dear Johny, try this:
hashtag=lower(input('Which hashtag would you like information on?','s'));
if isempty(strfind(hashtag, '#'))
error('Please include the hashtag')
end
Jos (10584)
Jos (10584) 2013년 12월 3일

0 개 추천

Per definition a hashtag starts with a # sign followed by one or more letters or numbers
So, quite simply, check all these three requirements:
str = lower(input('Which hashtag would you like information on?','s'));
if numel(str)<2 || str(1) ~= '#' || ~all(ismember(str(2:end),['a':z' '_' '0':'9']))
error('Input is not a valid hashtag') ;
end

카테고리

도움말 센터File Exchange에서 Mathematics에 대해 자세히 알아보기

질문:

2013년 12월 3일

댓글:

2013년 12월 3일

Community Treasure Hunt

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

Start Hunting!

Translated by