In: Computer Science
5.16 Implement function indexes() that takes as input a word (as a string) and a onecharacter letter (as a string) and returns a list of indexes at which the letter occurs in the word.
>>> indexes('mississippi', 's')
[2, 3, 5, 6]
>>> indexes('mississippi', 'i')
[1, 4, 7, 10]
>>> indexes('mississippi', 'a')
[]
def indexes(n,n1):
l=[]
j=0
for i in range(len(n)):
if(n[i]==n1):
l.append(i)
return l
n=input("Enter a string : ")
n1=input("Enter a character to check : ")
if(len(n1)!=1):
print("You enter only one character ")
n1=input("Enter a character to check : ")
print(indexes(n,n1))
Here is the python program that will asks the user to enter the string and then asks the user to enter a character and we call the function indexes() and in that function we are will iterate through the loop and then we compare each character of the string to the character and then append them to the list and finally return the list and print it.
SCREENSHOT OF THE OUTPUT AND THE CODE:
You can refer the photo for intendation in the code as python uses intendation.
I am providing you the code in ajva below but for exact output you better use python
import java.util.*;
class Main
{
public int[] insert(String s,char c)
{
int [] a=new int[s.length()];
int j=0;
for(int i=0;i<s.length();i++)
{
if(s.charAt(i)==c)
{
a[j]=i;
j++;
}
}
return a;
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
Main m=new Main();
System.out.print("Enter the string : ");
String s=sc.nextLine();
System.out.print("Enter a character to search : ");
char c = sc.next().charAt(0);
int a[]=m.insert(s,c);
for(int i=0;i<s.length();i++)
{
if(a[i]==0)
break;
System.out.print(a[i]+" ");
}
}
}
Here the screenshot of th code is not provided as there is no need of intendation in java.
SCREENSHOT OF THE OUTPUT: