Find exact pattern in string

조회 수: 3 (최근 30일)
Jasmien Sihota
Jasmien Sihota 2021년 2월 18일
답변: Walter Roberson 2021년 2월 18일
I am trying to find the exact pattern in my array including the number of characters.
clear all; close all;
code = ...
[".----";"..---";"...--";"....-";".....";"-....";"--...";"---..";"----.";...
"-----";".-";"-...";"-.-.";"-..";".";"..-.";"--.";"....";"..";".---";...
"-.-";".-..";"--";"-.";"---";".--.";"--.-";".-.";"...";"-";...
"..-";"...-";".--";"-..-";"-.--";"--..";"..--.-"];
letter = ...
["1";"2";"3";"4";"5";"6";"7";"8";"9";"0";"A";"B";"C";"D";"E";"F";"G";"H";...
"I";"J";"K";"L";"M";"N";"O";"P";"Q";"R";"S";"T";"U";"V";"W";"X";"Y";"Z";"-"];
userInput = input("Enter your morse code ", 's');
numcharacters = count(userInput, "/")
for i = 1:length(numcharacters)
if ismember (userInput(i), code)
k = strmatch(code,userInput(i), 'exact')
message = letter(k)
else
disp('error')
end
end
This version of the code outputs an empty array for k
When I change it to
k = matches(code,userInput(i))
it only matches to "T" or "E". I need to match the whole pattern for my code.

채택된 답변

Walter Roberson
Walter Roberson 2021년 2월 18일
Your code is expecting userInput(i) to be an entire group of pulses. But it is not. userInput is a character vector and (i) is indexing individual characters.
You have three choices:
1. remove the 's' option from input() and require that the user enter in the form
["..-","-"]
with your program crashing if they make a mistake; or
1b) same but put in a try/catch to handle the inevitable errors more smoothly; or
2. Leave in the 's' but expect the user to use the above form but scan the character vector to ensure that it has the right format, and use eval() on the validated character vector;
3. Leave in the 's' and continue to expect the user to use / to mark the end of blocks, and split the character vector into pieces at each / and string() the cell array of character vectors you got from the splitting to create the string array that you can use (i) indexing with.

추가 답변 (0개)

카테고리

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

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by