c++类实现字符串的基本函数

//--------------------------------------------------------
//date:2015/08/11/20:12
//author: fangchang
//包括读写,复制,连接,比较等函数
//字符串的惯用话(寻找\0的地址 复制 )
//itoa考虑是否为负数,考虑进制(比较烦,8进制的首位是0,16进制是0X)
//----------------------------------------------------------
#ifndef _STRING_DEMO_H
#define _STRING_DEMO_H
#include"stdio.h"
#include<iostream>
using namespace std;

class STRING{
public:
	int read_line(char str[], int n) ;             //读字符串
	char * strcpy(char *str1, const char * str2) ; //复制
	char * strcat(char *str1, const char * str2) ; //连接
	int strcmp(const char * str1, const char *str2 ) ; //比较
	char * itoa(char * str1,int value);                //int转成字符串(考虑负数)
	void print(char *str) ;                            //打印
};

int STRING::read_line(char str[], int n) {
	int i=0;
	while(i<n) {
		char ch=getchar();
		if( '\n'!= ch ) {
			str[i++]=ch;
		}
		else {
			break;
		}
	}
	str[i]='\0';
	return i;
}

void STRING::print(char *str) {
	printf("string is: %s\n",str);
}

char * STRING::strcpy(char *str1, const char *str2) {
	if(NULL==str1 || NULL==str2 ) {
		return NULL;
	} 
	char *res = str1;
	while( '\0' != (*str1++ = *str2++) ) {  //复制的实现原理: 修改指针指向的地址中的值
		;
	}
	return res;
}
  
char * STRING::strcat(char *str1, const char *str2) {
	if(NULL==str1 || NULL==str2) {
		return NULL;
	}
	char *res =str1;
	while( '\0' != *str1 ) {
		str1++;
	}
	while( '\0' != (*str1++=*str2++) ) {
		;
	}
	return res;
}

int STRING::strcmp(const char *str1, const char * str2 ) {
	if(NULL==str1 || NULL==str2) {
		return NULL;
	}
	while('\0'!=*str1 && '\0' != *str2 && *str1==*str2) {
		++str1;
		++str2;
	}
	int res = *str1 - *str2;
	if(0 == res) {
		return 0;
	}
	else if(res < 0) {
		return -1;
	}
	else {
		return 1;
	}
}

char * STRING::itoa(char * str1, int value) {
	int tmp;
	char flag;
	char str[16];
	int i=0;
	int j=0;
	int k=0;
	if(value<0) {
		tmp=0-value;
		flag='-';
	}
	else {
		tmp=value;
	}
	do{
		int number=tmp%10;
		char ch = (char)(number + '0');
		str[i++]=ch;
		tmp=tmp/10;
	}while(0 != tmp);
	for(j=i-1;j>=0;--j) {
		str1[k++]=str[j];
	}
    str1[k]='\0';
	if('-'==flag) {
		for(j=k;j>=0;--j) {
			str1[j+1]=str1[j];
		}
		str1[0]=flag;
	}
	return str1;
}
#endif




#include"stringDemo.h"
#define STR_LEN 80

int main() {
	char str[STR_LEN+1];
	char str2[STR_LEN+1];

	STRING * _string =new STRING;
	_string->read_line(str,STR_LEN);
	_string->print(str);
	
	cout<<"begin copy: "<<endl;
	if(NULL != _string->strcpy(str2,str) ) {
		_string->print(str2);
	}
	if(NULL != _string->strcat(str2,"456") ) {
		_string->print(str2);
	}
	cout<<_string->strcmp("a","b")<<endl;
	int num=-123121;
	char str3[16];
	_string->print(_string->itoa(str3,num));
	system("pause");
	return 1;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值