经典面试题--字符串转换,复制,倒置

1   怎样用整数转换为字符串,不用函数itoa?

直接代码:

#include <iostream>

using namespace std;

int main()
{
    int num = 12345;
    int i = 0,j = 0;
    char temp[7],str[7];
    while(num > 0)
    {
        temp[i++] = num%10 + '0';
        num=num/10;
    }
    temp[i] = '\0';
    cout << "temp: " << temp << endl;
    i = i-1;
    while(i >= 0)
    {
        str[j++] = temp[i--];
    }
    str[j] = '\0';
    cout << "str: " << str << endl;

    return 0;
}

2  重新编写strcpy函数  原型:char *strcpy(char *strDest,const char *strSrc)

char *strcpy(char *strDest,const char *strSrc)
{
    assert((strDest!=NULL)&&(strSrc!=NULL));
    char *address=strDest;
    while((*strDest++=*strSrc++)!='\0');
    return address;
}

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

#include <iostream>
#include <stdlib.h>
#include<string.h>
using namespace std;

#define MAX_LEN 10;
void looprightMove(char *src,int steps)
{
    int n = strlen(src)-steps;
    char *temp;
    temp = (char *)malloc(strlen(src)+1);
    strcpy(temp,src+n);
    src[n]='\0';
    strcpy(temp+steps,src);
    strcpy(src,temp);
    free(temp);
}
int main()
{
    char str[10] = "sanwan";
    looprightMove(str,2);
    cout << "str: " << str << endl;

    return 0;
}

4    将一句话里的单词进行倒置,标点符号不倒置。比如一句话:i come from beijing.倒置后变成:beijing. from come i。

#include <iostream>
#include<string.h>
using namespace std;
int main ()
{
int i = 0,j = 0,flag = 0,begin = 0,end = 0;
char str[]="i come from beijing.";
char temp;
j=strlen(str)-1;
while(j>i)
{
temp=str[i];
str[i++]=str[j];
str[j--]=temp;
}
i=0;
while(str[i])
{
if(str[i]!=' ')
{
begin=i;
while(str[i] && str[i]!=' ')
i++;
i=i-1;
end=i;
}
while(end>begin)
{
temp=str[begin];
str[begin++]=str[end];
str[end--]=temp;
}
i++;
}
cout<<"string:"<<str<<endl;
}

5    编程:输入一行字符串,找出其中出现的相同且长度最长的字符串,输出它及其首字符的位置。例如:“yyabcdabjcabceg”,输出结果应该为 abc和 3


#include <iostream>
#include <string>
using namespace std;

int main ()
{
    string str,tep;
    cout<<"请输入字符串:";
    cin>>str;

    for(int i=str.length()-1;i>1;i--)
    {
        for(int j=0;j<str.length();j++)
        {
            if(j+i<=str.length())
            {
                size_t t=0;
                size_t num=0;
                tep=str.substr(j,i);//从大到小去字串
                t=str.find(tep);    //正序查找
                num=str.rfind(tep); //逆序查找
                if(t!=num)          //如果两次查找的位置不一致说明存在重复
                {
                    cout<<tep<<" "<<t+1<<endl;
                    return 0;
                }
            }
        }
    }
    return 0;
}


(本人微博:http://weibo.com/u/2729471010/home?wvr=5   微信号:yuansanwan,欢迎一起讨论问题)

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值