Hello,
How to find the location of first occurance & last occurance of a specified character in a given string !!
Thanks in advance !!
Regards,
Hari
Hello,
How to find the location of first occurance & last occurance of a specified character in a given string !!
Thanks in advance !!
Regards,
Hari
Code:#include<stdio.h> #include<string.h> int main() { char str[] = "Hello"; printf("First %c and last %c ocurrances.\n", str[0], str[ strlen(str) - 1] ); return 0; }
Or if that wasn't quite what you wanted than use 'strchr' standard library function to find a character in a string.
STRCHR(3) Linux Programmer's Manual STRCHR(3)
NAME
strchr, strrchr - locate character in string
SYNOPSIS
#include <string.h>
char *strchr(const char *s, int c);
char *strrchr(const char *s, int c);
DESCRIPTION
The strchr() function returns a pointer to the first occurrence of the
character c in the string s.
The strrchr() function returns a pointer to the last occurrence of the
character c in the string s.
Here "character" means "byte" - these functions do not work with wide or
multi-byte characters.
RETURN VALUE
The strchr() and strrchr() functions return a pointer to the matched char-
acter or NULL if the character is not found.
CONFORMING TO
SVID 3, POSIX, BSD 4.3, ISO 9899
Code:int find_firstlast(char *str,char chr,int *first,int *last){ char *pstr = str; int len = strlen(str); *first = -1; *last = -1; /*invalid */ /*find first*/ while(*pstr){ if(*pstr == chr) { *first = (int)(pstr - str); break; } pstr++; } if(*first == -1) return -1; /*First not found!... abort...*/ /*find last*/ pstr = str + len; while(pstr>=str){ /*there WAS a missing line... don't mind the next post :) */ if(*pstr == chr) { *first = (int)(pstr - str); break; } pstr--; } if(*last == -1) return -2;/*last occurance not found ... abort*/ return 0;/*succes ! both are found*/ } int main(void){ char test[] = "This is a test string"; int ret = 0; int first,last; if((ret=find_firstlast(test,'i',&first,&last)) < 0) { switch (ret) { case -1: printf("First not found\n"); break; case -2: printf("Last not found\n"); break; default: printf("Unknown Error\n"); } } else { printf("'%c' found at %d and %d locations\n", 'i',first,last); } return 0; }
Last edited by borko_b; 07-17-2002 at 09:30 AM.
OOPS!!
should be:Code:... while(pstr!=) { ...
Code:while(pstr >= str) {