Hatena::Groupcprogramming

てーげーC言語

2009-03-04

[K&R}4-1

| 00:41

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

void reverse(char* s)
{
  int i, j;
  char temp, *p;

  i = j = 0;
  p = s;


  while(*p++) {
    i++;
  }

  --i;
  while(i > j) {
    temp = *(s+i);
    *(s+i) = *(s+j);
    *(s+j) = temp;
    i--;
    j++;
  }
}

int strrindex(char* s, char* t) {
  int len, i, j;

  len = strlen(s);
  i = len;

  reverse(t);

  while(i-- >= 0) {
    for(j = 0; (*(s+i) == *(t+j)) &&  (*(t+j) != '\0'); i--, j++) {
    }   

    if (*(t+j) == '\0')
      return i+1;
  }
  return -1; 
}

int main()
{
  char* s = "helloworld";
  char t[] = "world";
  char* u = "hogebarfuga";
  char v[] = "bar";
  char* w = "rubyperlphp";
  char x[] = "java";
  char* y = "helloworldhelloworld";
  char z[] = "hello";
  int rtn;

  rtn = strrindex(s, t);
  printf("%d\n", rtn);

  rtn = strrindex(u, v);
  printf("%d\n", rtn);

  rtn = strrindex(w, x);
  printf("%d\n", rtn);

  rtn = strrindex(y, z);
  printf("%d\n", rtn);

  return 0;
}
# ./a.out                
5
4
-1
10