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)

采纳的回答

Image Analyst
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 个评论
Oblique
Oblique 2020-5-16
actually first code you write more clear than the other.I can understand what you write easily thanks for your help :)
Image Analyst
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
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 个评论
Rik
Rik 2020-5-16
编辑:Rik 2020-5-16
I see no reason why this wouldn't work in Octave. I just tested it on 5.1.0 and it worked as expected. What errors are you getting?
Oblique
Oblique 2020-5-16
编辑:Oblique 2020-5-16
it did not work before but it worked now i dont know why happened like this. Thanks again

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Octave 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by