lolamontes69

K+R Exercise2_5

Sep 5th, 2014
249
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.19 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. int any(char s1[], char s2[]);
  4.  
  5. int main()
  6. {
  7.     int c, i, n;
  8.     char s1[255];
  9.     char s2[255];
  10.    
  11.     printf("Enter a string >");
  12.     i=0;
  13.     while((c=getchar())!=EOF && c!='\n') {
  14.         s1[i]=c;
  15.         ++i;
  16.     }                      
  17.     s1[i]='\0';      // doesn't automatically add '\0'
  18.  
  19.     n=0;
  20.     printf("Enter characters to find in string >");
  21.     while((c=getchar())!=EOF && c!='\n') {
  22.         s2[n]=c;
  23.         ++n;
  24.     }                      
  25.     s2[n]='\0';
  26.  
  27.     if(i==0) printf("\n<<<Try using data>>>\n");
  28.     else {
  29.         i=any(s1, s2);
  30.         if(i==-1) puts("\nNo search results");
  31.         else printf("any(s1,s2) returned index %d\n",i);
  32.     }
  33.     return(0);
  34. }
  35.  
  36. int any(char s1[], char s2[])
  37. {
  38.     int a, i;  // outer loop, inner loop
  39.     int best;  // the first location in the string where character encountered
  40.  
  41.     best = -1;
  42.     for(a = 0; s2[a] != '\0'; a++) {
  43.         for(i = 0; s1[i] != '\0'; i++) {
  44.             if(s1[i] == s2[a]) {
  45.                 if(best==-1)
  46.                     best=i;
  47.                 else if(i<best)
  48.                     best=i;
  49.             }
  50.         }
  51.     }
  52.     return best;
  53. }
Advertisement
Add Comment
Please, Sign In to add comment