Never underestimate the power of Passion!

Tuesday 14 February 2017

On 02:13 by Vardan Kumar in    No comments
C String Character Position
Function which takes string and a character as input and returns the next position of character each time it is called

Today we'll define a function with following properties:-

  1. Return type of the function will be int i.e. the function will return an integer value.
  2. Function will accept two arguments.
  3. One of the argument will be a char and another char array.
Now let us try to understand our purpose with the help of an example......

Suppose our input string is: The domain name of this website is www.cspassion.com
and Suppose our input character is: 'i'

Then our function should do the following...
After 1st call-> 9
After 2nd call->22
After 3rd call->29
After 4th call->33
After 5th call->46

There by if any more calls are made to the function then "No more occurrences" kind of message should be displayed.

Hope the purpose is understood, lets give it a shot before proceeding further......

Logic:

  1. We'll use infinite while loop which will include switch-case control inside it.
  2. One case will make a call to function and another will bt he exit case.
  3. We'll use static variable as function's local variable so that its previous value is not lost whenever a new call is made to the function.
C Program for string-character position program
Output String-Character position Program

Source code


#include<stdio.h>
int get_position(char linput,char linput1[100])
{
    static int count=0;
    while(linput1[count]!=linput)
    {
        count=count+1;
    }
       count=count+1;
    return count;
}
void main()
{
    int count=0,pocket,choice,i,count1=0;
    char input,input1[100];
    printf("Enter the String\n");
    fflush(stdin);
    fgets(input1,sizeof(input1),stdin);
    printf("\nEnter the character whose position you want to return:");
    scanf("%c",&input);
    for(i=0;i<strlen(input1);i++)
    {
        if(input1[i]==input)
            count1++;
    }
    while(1)
    {
    printf("\nEnter 1 to call the function,it would be your call '%d'\n",count+1);
    printf("\nEnter 2 for exit\n");
    printf("Enter your choice:");
    scanf("%d",&choice);
        switch(choice)
        {
            case 1:
                count=count+1;
                if(count<=count1)
                {
                fflush(stdin);
                pocket=get_position(input,input1);
                printf("\nAfter call %d,the position is %d\n",count,pocket);
                }
                else{
                    printf("No more occurrences of the specified character");
                    exit(1);
                }
                break;
            case 2:
                exit(1);
                break;
            default:
                printf("Invalid input\n");
                break;
        }

    }
}





0 comments:

Post a Comment