Borrar filtros
Borrar filtros

Hello. I have to write a function called occurrence that tests whether a character exists in a string. If it is present, display true and the position (index) of the character. If it is not present, return inf. it gives me an error in line 2. help?!?

1 visualización (últimos 30 días)
function find_letter(L, string)
n= 1:length(L);
not_found = true;
for k = 1:n
if isequal(L(k).letter, string)
fprintf('letter %s is present! It is the %2.0d item\n', L(k).title, k);
not_found = false;
break; % or return
end
end
if not_found; fprintf('letter not present\n')
end
  2 comentarios
Rik
Rik el 19 de Dic. de 2019
How do you call this function? Also, you're generating a vector for your loop twice, and you haven't set the output to inf yet.
Naagy Omar
Naagy Omar el 19 de Dic. de 2019
Editada: Naagy Omar el 19 de Dic. de 2019
thank you my friend!
Ive edited the code, but it still gives me an error. i tried just clicking "run" but it doesn't work. I also tried calling the function using "find_character('itscoldtoday, o')" but it returns error in line 3.
function find_character(L, string)
not_found = true;
for k = 1:length(L);
if isequal(L(k).character, string)
fprintf('character %s is present! It is the %2.0d item\n', L(k).title, k);
not_found = false;
break; % or return
end
end
if not_found; fprintf('Inf\n')
end
end

Iniciar sesión para comentar.

Respuesta aceptada

Chuguang Pan
Chuguang Pan el 19 de Dic. de 2019
function find_letter(L, string)
n= length(L);
not_found = true;
for k = 1:n
if isequal(L(k), string)
fprintf('letter %s is present! It is the %2.0d item\n', L(k), k);
not_found = false;
break; % or return
end
end
if not_found; fprintf('letter not present\n')
end
find_letter('Hello World!','o');
  2 comentarios
Naagy Omar
Naagy Omar el 19 de Dic. de 2019
Thank you for your help! Hey I tried this and it works!
find_letter('itscoldtoday!','y');
function find_letter(L, string)
not_found = true;
for k = 1:strlength(L);
if isequal(L(k), string)
fprintf('letter %s is present! It is the %2.0d item\n', L(k), k);
not_found = false;
break; % or return
end
end
if not_found; fprintf('letter not present\n')
end
end

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by