Q:

Find last index of a character in a string using C++ program

0

Find last index of a character in a string using C++ program

Given a string, and we have to find last index of a character using C program.

Examples:

Enter string: Hello world!
Enter character: o
Last index of 'o' is: 7 

Enter string: Hello world!
Enter character: H
Last index of 'H' is: 0 

Enter string: Hello world!
Enter character: z
'z' is not found in the string

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

  • Read a string str and character ch whose last index to be found.
  • Get the length of the string (length).
  • Run loop from length-1 to 0.
  • Check character with each character of the string, if it is found return the index (loop counter's value) (which will be the result).
  • If character not found (after the loop), return -1.
  • Call the function in the main program, if return value is -1 that means character not found in the string else store the index in the variable (index).
  • Print the index.

Consider the program:

#include <iostream>
#include <string.h>
using namespace std;

//function to get lastt index of a character 
int getLastIndex(char *s, char c)
{
	int length;
	int i; //loop counter
	//get length
	length = strlen(s);
	
	//run loop from length-1 to 0
	for(i=(length-1); i>=0; i--)
	{
		//compare character with each charater of string
		if(s[i]==c)
			return i; //character found return index
	}
	
	//if character not found return -1
	return -1;	
}

//main programs
int main()
{
	char str[100]; //maximim 100 characters
	char ch; //character to find
	int index;  //to store index
	
	cout<<"Enter string: ";
	//read with spaces too
	cin.getline(str,100);
	
	cout<<"Enter character: ";
	cin>>ch;
	
	index = getLastIndex(str,ch);
	
	//if index is not -1 then print its index
	if(index!=-1)
		cout<<"Last index of \'"<<ch<<"\' is: "<<index<<endl;
	else
		cout<<"\'"<<ch<<"\' is not found in the string"<<endl;
		
	return 0;	
}

Output

First run:
Enter string: Hello world!
Enter character: o
Last index of 'o' is: 7 

Second run:
Enter string: Hello world!
Enter character: H
Last index of 'H' is: 0 

Third run:
Enter string: Hello world!
Enter character: z
'z' is not found in the string 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now