/*
* String.c
*
* Created on: 2012-12-4
* Author: Administrator
*/
#include <stdio.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
#define CHECK(t) do{if(!(t))return 0;}while(0)
typedef char* String;
typedef int Status;
static String STRBUFFER = 0;
int StrLen(String buf){
String temp = buf;
while(*temp++);
return temp-buf-1;
}
String StrMake(int length){
return (String)malloc(length+1);
}
String StrChr(String buf, char ch, int length){
while(length--&&*buf++ != ch);
return buf-1;
}
void StrCat(String *dest,String src){
String temp = (String)malloc(StrLen(*dest)+StrLen(src)+1);
String head = temp;
String d = *dest;
while(*d){
*temp++ = *d++;
}
while(*src){
*temp++ = *src++;
};
*temp = '\0';
*dest = head;
}
int StrCmp(String buf1,String buf2){
do{
if(*buf1>*buf2)return 1;
if(*buf1<*buf2)return -1;
if(!*buf1)break;
buf1++;
buf2++;
}while(1);
return 0;
}
void StrCpy(String *dest,String src){
*dest = StrMake(StrLen(src));
String temp = *dest;
while(*src){
*temp++=*src++;
}
*temp = 0;
}
void StrFree(String *str){
free(*str);
*str = 0;
}
Status StrPrint(String str){
CHECK(str);
puts(str);
return TRUE;
}
String StrTok(String dest,String src){
if(dest)StrCpy(&STRBUFFER,dest);
CHECK(src&&STRBUFFER&&*STRBUFFER);
int length = StrLen(src);
String ch = StrChr(src, *STRBUFFER, length);
if(*ch == *STRBUFFER){
do{
*STRBUFFER++='\0';
CHECK(*STRBUFFER);
ch = StrChr(src, *STRBUFFER, length);
}while(*ch == *STRBUFFER);
}
String result = STRBUFFER;
String temp = result;
while(*temp) {
ch = StrChr(src, *temp, length);
if (*ch == *temp) {
*temp++ = '\0';
CHECK(*temp);
break;
}else{
temp++;
}
}
STRBUFFER = temp;
return result && *result ? result : 0;
}
String StrStr(String dest,String src){
CHECK(dest&&src&&*dest&&*src);
do{
String temp = src,rt = dest;
while(*temp == *rt){
temp++;rt++;
}
if(!*temp)return dest;
CHECK(*rt);
dest++;
}while(*dest);
return 0;
}