1. 整數轉換成字符串 itoa 函數的實現
#include "stdafx.h"
#include <iostream>
using namespace std;
void itoaTest(int num,char str[] )
{
int sign = num,i = 0,j = 0;
char temp[11];
if(sign<0)// 判斷是否 是一個負數
{
num = -num;
};
do
{
temp[i] = num%10+'0';
num/=10;
i++;
}while(num>0);
if(sign<0)
{
temp[i++] = '-';
}
temp[i] = '/0';
i--;
while(i>=0)
{
str[j] = temp[i];
j++;
i--;
}
str[j] = '/0';
}
2. // 字符串轉換成整數 atoi 函數的實現
int atoiTest(char s[])
{
int i = 0,sum = 0,sign; // 輸入的數前面可能還有空格或製表符應加判斷
while(' '==s[i]||'/t'==s[i])
{
i++;
}
sign = ('-'==s[i])?-1:1;
if('-'==s[i]||'+'==s[i])
{
i++;
}
while(s[i]!='/0')
{
sum = s[i]-'0'+sum*10;
i++;
}
return sign*sum;
}
3.// 字符串拷貝函數
#include "stdafx.h"
#include <assert.h>
#include <string.h>
#include <iostream>
using namespace std;
char *srcpy(char *dest,const char *source)
{
assert((dest!=NULL)&&(source!=NULL));
char *address = dest;
while(*source!='/0')
{
*dest++=*source++;
}
*dest = '/0';
return address;
}
4.// 判斷輸入的是否是一個迴文字符串
#include "stdafx.h"
#include <string.h>
#include <iostream>
using namespace std;
//方法一:藉助數組
bool isPalindrome(char *input)
{
char s[100];
strcpy(s,input);
int length = strlen(input);
int begin = 0,end = length-1;
while(begin<end)
{
if(s[begin]==s[end])
{
begin++;
end--;
}
else
{
break;
}
}
if(begin<end)
{
return false;
}
else
{
return true;
}
}
//方法二:使用指 針
bool isPalindrome2(char *input)
{
if(input==NULL)
return false;
char *begin = input;
char *end = begin+strlen(input)-1;
while(begin<end)
{
if(*begin++!=*end--)
return false;
}
return true;
}
int main(int argc, char* argv[])
{
char *s ="1234554321";
if(isPalindrome(s))
{
cout<<"True"<<endl;
}
else
{
cout<<"Fasle"<<endl;
}
if(isPalindrome2(s))
{
cout<<"True"<<endl;
}
else
{
cout<<"Fasle"<<endl;
}
cin.get();
return 0;
}
5.// 不使用庫函數,編寫函數 int strcmp(char *source, char *dest) ,若相等返回 0 ,否則返回 -1
<pre name="code" class="cpp"><span style="font-family:SimSun;">int strcmp(char *source, char *dest)
{
assert(source != NULL && dest != NULL);
while(*source++==*dest++)
{
if(*source=='/0'&&*dest=='/0')
return 0;
}
return -1;
}</span>