[C++面试题]之字符串

[C++面试题]之字符串

      基本上求职者进行笔试时没有不考字符串的。字符串也是一种相对简单的数据结构,容易引起面试官反复发问。事实上,字符串也是考验程序员编程规范和编程习惯的重要考点。不要忽视这些细节,因为这些细节会体现你在操作系统、软件工程、边界内存处理等方面的知识掌握能力,也会成为企业是否录用你的参考因素。

1、怎样将整数转换成字符串数,并且不用函数 itoa ?

    答案:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
using  namespace  std;
 
int  main ()
{
     int  num =12345,i=0,j=0;
     char  temp[7],str[7];
     while (num)
     {
         temp[i]=num%10+ '0' ; //将整数num从后往前的每一位数转换成char保存在temp中
         i++;
         num=num/10;
     }
     temp[i]=0;
     cout<< "temp:" <<temp<<endl;
     i=i-1;
     //反转temp
     while  (i>=0)
     {
         str[j++]=temp[i--];
     }
     str[j]=0;
     cout<< "string:" <<str<<endl;
     return  0;
}

 

    如果可以使用 itoa函数的话,则十分简单,如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <stdlib.h>
using  namespace  std;
 
//使用itoa函数
int  main ()
{
     int  num=12345;
     char  str[7];
 
     itoa(num,str,10);
     cout<< "integer:" <<num<<endl<< "string:" <<str<<endl;
     return  0;
}

 

2、已知函数原型是 char *strcpy(char *strDest,const char *strSrc);,其中strDest是目的字符串,strSrc是源字符串。

    (1)不调用C++/C的字符串库函数,请编写strcpy函数。

    (2)strcpy函数把strSrc的内容复制到strDest,为什么还要char *类型返回值?

    答案:

(1)代码如下:

1
2
3
4
5
6
7
8
char  * strcpy ( char  *strDest, const  char  *strSrc)
{
     assert ((strDest!=NULL)&&(strSrc!=NULL));
     char  *address=strDest;
     while ((*strDest++=*strSrc++)!= '\0' )
     NULL;
     return  address;
}

(2)为了实现链式表达式,返回具体值。

例如:

1
int  length= strlen ( strcpy (strDest, "hello world" ));

 

3、编写一个函数,作用是把一个char组成的字符串循环右移n个。比如原来是" abcdefghi “,如果n=2,移位后应该是 “hiabcdefg ”。

    答案:

(1)使用标准库函数方法:

1
2
3
4
5
6
7
8
9
void  LoopMove( char  *pStr, int  steps)
{
     int  n= strlen (pStr)-steps;
     char  temp[MAX_LEN];
     strcpy (temp,pStr+n);
     strcpy (temp+steps,pStr);
     *(temp+ strlen (pStr))=‘\0’;
     strcpy (pStr,temp);
}

(2)不使用标准库函数的方法:

优快云上一道题(请看第五题和评论)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值