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,欢迎一起讨论问题)