top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Write a function that finds the last instance of a character in a string?

+1 vote
307 views
Write a function that finds the last instance of a character in a string?
posted Nov 27, 2015 by Mohammed Hussain

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

Format

#include <string.h>
char *strrchr(const char *string, int c);

Language Level
ANSI

Threadsafe
Yes

Locale Sensitive
The behavior of this function might be affected by the LC_CTYPE category of the current locale. For more information

Description
The strrchr() function finds the last occurrence of c (converted to a character) in string. The ending null character is considered part of the string.

Return Value
The strrchr() function returns a pointer to the last occurrence of c in string. If the given character is not found, a NULL pointer is returned.

Example
This example compares the use of strchr() and strrchr(). It searches the string for the first and last occurrence of p in the string.

#include <stdio.h>
#include <string.h>

#define SIZE 40

int main(void)
{
  char buf[SIZE] = "computer program";
  char * ptr;
  int    ch = 'p';

  /* This illustrates strchr */
  ptr = strchr( buf, ch );
  printf( "The first occurrence of %c in '%s' is '%s'\n", ch, buf, ptr );

  /* This illustrates strrchr */
  ptr = strrchr( buf, ch );
  printf( "The last occurrence of %c in '%s' is '%s'\n", ch, buf, ptr );
}

/*****************  Output should be similar to:  *****************

The first occurrence of p in 'computer program' is 'puter program'
The last occurrence of p in 'computer program' is 'program'
*/
answer Nov 27, 2015 by Shivaranjini
Similar Questions
+6 votes

For example: It returns ‘b’ when the input is “abaccdeff”.

+4 votes

If we delete the mth number from a circle which is composed of numbers 0, 1, …, n-1 counting from 0 at every time, what is the last number?

For example, a circle is composed of five numbers 0, 1, 2, 3, 4. If we delete the 3rd number at every time, the deleted numbers are in order of 2, 0, 4, 1, so the last remaining number is 3.

+3 votes

Given a string and a positive integer d. Some characters may be repeated in the given string. Rearrange characters of the given string such that the same characters become d distance away from each other. Note that there can be many possible rearrangements, the output should be one of the possible rearrangements.

example:
Input:  "abb", d = 2
Output: "bab"
...