第五章中的习题5-3,5-4,5-5
// 5_5_pointer.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<stdio.h>
#include<iostream>
using namespace std ;
void strcpy_1(char *s , char *t);
void strcpy_2(char *s , char *t);
void strcat(char *s , char *t);
int strend(char *s , char *t);
void strncpy_(char *s ,char *t , int n);
void strncat_(char *s ,char *t , int n);
int strncmp_(char *s , char *t , int n);
int _tmain(int argc, _TCHAR* argv[])
{
char s[] = "youlo you!";
char t[] ="you!";
// strcpy_1(s , t);
// strcpy_2(s , t);
// cout<<s <<endl;
// strcat(s,t);
// cout<<s <<endl;
// cout<<strend(s,t)<<endl;
// strncpy_(s,t,3);
strncat_(s,t,3);
cout<<s <<endl;
cout<<strncmp_(s,t,3)<<endl;
getchar();
return 0;
}
/************习题5-3************/
void strcat(char *s , char *t)
{
while(*s != '\0')
s++ ;
while((*s++ = *t++) != '\0')
;
*s = *t ;
}
/************习题5-4************/
int strend(char *s , char *t)
{
char *begin_s = s ;
char *begin_t = t ;
//将两个指针都移动到字符串的末尾,从后向前一一进行比较
for(; *s != '\0' ; s++)
;
for(; *t != '\0' ; t++)
;
for(; *s == *t ; s-- , t--)
{
if(t == begin_t || s == begin_s)
break;
}
if(t == begin_t)
return 1 ;
return 0 ;
}
/************习题5-5************/
void strncpy_(char *s ,char *t , int n)
{
for( ;n > 0 ; t++ , s++ ,n--)
{
*s = *t;
}
if(*s != '\0')
*s = '\0';
}
//把t所指字符串的前n个字符添加到s结尾处(覆盖dest结尾处的'\0')并添加'\0'。
void strncat_(char *s ,char *t , int n)
{
while(*s != '\0')
s++;
for( ;n > 0 ; t++ , s++ ,n--)
{
*s= *t;
}
if(*s != '\0')
*s = '\0';
}
//比较字符串str1和str2的前n个字符
int strncmp_(char *s , char *t , int n)
{
for(; *s == *t ; s++ , t++)
{
n--;
if(*s == '\0' || n <= 0)
return 0 ;
}
if( (*s - *t) > 0)
return 1 ;
else
return -1 ;
}
//将t中的内容复制到s中,此时s当中原有的字符已不存在
void strcpy_1(char *s , char *t)
{
int i = 0 ;
while((s[i] = t[i]) != '\0')
i++;
}
void strcpy_2(char *s , char *t)
{
while((*s = *t) != '\0')
{
s++ ;
t++ ;
}
}