Saturday, September 22, 2018

Word index 1

  • Problem Description

    Write a C program to find the first occurrence of word in a string using loop

    Refer sample Input and Output:
    Example 1: 
    srm university
    university
    Output 1: university is found at 4

    The String university is found at string index 4. Array Index starts from 0

    Example 2:
    srm university
    universit

    Output 2:
    universit is not found
  • CODING ARENA
  • #include <stdio.h>
    #include <string.h>
    #define MAX_SIZE 100

    int main()
    {
        char str[MAX_SIZE];
        char word[MAX_SIZE];
        int i, j, found;
        int strLen, wordLen;


        scanf("%[^\n]%*c",str);
        scanf("%s",word);

        strLen  = strlen(str);  
        wordLen = strlen(word); 


        for(i=0; i<strLen; i++)
        {

            found = 1;
            for(j=0; j<wordLen; j++)
            {
           
                if(str[i + j] != word[j])
                {
                    found = 0;
                    break;
                }
            }


            if(found == 1)
            {
                printf("%s is found at %d\n",word,i);
            }
        }

        return 0;
    }
  • Test Case 1

    Input (stdin)
    srm apple lab in UB block
    
    apple
    
    
    Expected Output
    apple is found at 4
  • Test Case 2

    Input (stdin)
    srm applelab in UB block
    
    lab
    
    
    Expected Output
    lab is found at 9

No comments:

Post a Comment