钟铃演员:字符串面试题

来源:百度文库 编辑:九乡新闻网 时间:2024/05/07 09:12:04

一般面试字符串的题目分四种:1, 基本运算(求长度,连接,比较)2. 格式转换(atoi, itoa) 3.字符串翻转 4. 模式匹配。

1. 基本运算

a. 赋值操作

函数原型:int StrAssign(const char *s, char *t)

函数说明:将s的内容付给t

函数定义:

int StrAssign(const char *s, char *t){
 char *p = t;
  while(*s !='\0'){
  *p++ = *s++;
 }
 *p = '\0';

 return 0;
}

b. 连接操作

函数原型:int Concat(char *s, const char *t)

函数说明:将串t连接到串s的尾部,形成一个新串

函数定义:
int Concat(char *s, const char *t){
 //首先找到串s的尾部
 char *p = s;

 while(*p != '\0') p++;//循环结束以后的p就是s的尾部

  while(*t !='\0')   *p++ = *t++; 
  *p='\0';//添加尾部字符

  return 0;
}

c.求长度

函数原型:int StrLen(char *s)

函数说明:返回串s的长度

函数定义:

int StrLen(char *s){
 int len = 0;

 while(*s != '\0'){
  len ++;
  s++;
 }

 return len;
}

d. 字符串比较

函数原型:int StrCmp(const char *s, const char *t)

函数说明:比较两个串的大小,返回值为-1,0,1表示st。

函数定义:

int StrCmp(const char *s, const char *t){
 while((*s != '\0')&&(*t != '\0')){
   if(*s++ - *t++ > 0) return 1;
  else if( *s++ - *t++ <0) return -1;
  else return 0;
 }

 return 0;
}

//不区分大小写的字符串比较函数
int stricmp(const char *s, const char *t){ 
 while((*s != '\0')&&(*t != '\0')){  
  if(toupper(*s++) - toupper(*t++) > 0) return 1;
  else if(toupper(*s++) - toupper(*t++) <0) return -1;
  else return 0;
 }

 return 0;
}