How can i write 2D longest character array ?
1 次查看(过去 30 天)
显示 更早的评论
This array must be between two asterisk signs (*) and the code should give us the longest name in this array
For example: {'878*jhon*23 ; '*jonathan*87' ; '485*will*421'}
output will be as a 'jonathan'
I wrote code like this. but it's not what want.
a = {'23*Ali*36' ; 'Veli*178' ; '99*Zeynep*'} ;
for k=1:length(a)
val(k)=length(a{k});
x = findstr(a) , '*' )
end
out=a(val==max(val)
0 个评论
采纳的回答
Image Analyst
2020-5-16
编辑:Image Analyst
2020-5-16
Did you just try a super obvious brute force approach using a for loop:
a = {'23*Ali*36' ; 'Veli*178' ; '99*Zeynep*'} ;
nameLengths = zeros(length(a), 3); % Preallocate.
for k = 1 : length(a)
thisCellContents = a{k};
starLocations = find(thisCellContents == '*') % Find indexes of stars.
% Extract the name
if length(starLocations) >= 2
% Extract length between start #1 and star #2.
nameLengths(k, :) = [starLocations(1), starLocations(2), starLocations(2) - starLocations(1) + 1];
elseif length(starLocations) >= 1
% One star. Start from the beginning.
nameLengths(k, :) = [1, starLocations(1), starLocations(1)];
else
% No stars.
nameLengths(k, :) = [1, length(thisCellContents), length(thisCellContents)]; % The whole thing.
end
end
nameLengths % Report to command window.
[maxLength, row] = max(nameLengths(:,3)) % Find the longest one - biggest separation.
longestRow = a{row} % Get the entire string, including the start.
% Extract the substring.
out = longestRow(starLocations(1) + 1 : starLocations(2) - 1)
I'm sure there are less obvious, but more cryptic methods that are shorter if you want to wait for one from someone else.
4 个评论
Image Analyst
2020-5-16
You're welcome. Because comments are SO important, I added a few to make it even easier to follow. I encourage you to use descriptive variable names and lots of comments in your code. If my answer helped you maybe you could click the Vote button. Thanks in advance.
更多回答(1 个)
Ameer Hamza
2020-5-16
编辑:Ameer Hamza
2020-5-16
Try this
a = {'23*Ali*36' ; 'Veli*178' ; '99*Zeynep*'} ;
m = regexp(a, '[A-Za-z]*', 'match');
m = [m{:}];
[~, idx] = max(cellfun(@numel, m));
longest_name = m{idx};
Result
>> longest_name
longest_name =
'Zeynep'
5 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Octave 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!