标签:des style blog color os io ar 2014 div
1、strncpy字符串拷贝函数
//strncpy的程序 #include<stdio.h> #include<assert.h> char *strncpy1(char *strDest,const char *strSrc,int n) { assert((strDest!=NULL)&&(strSrc!=NULL)&&n>0); if(strDest==strSrc) return strDest; char *Address=strDest; while(n--&&(*strDest++=*strSrc++)!=‘\0‘) //n--必须放在前面,退出循环哪一步检测到n=0时,后一个判断条件就不做了 ; *(strDest)=‘\0‘; return Address; } int main() { char strDest[]="tyua"; char strSrc[]="abcd"; char *pDest=strDest; char *pSrc=strSrc; strncpy1(pDest,pSrc,4); printf("%s",pDest); }
2、右旋转字符串
//abcdef #include<stdio.h> #include<assert.h> #include<string.h> #include<malloc.h> void ReverseString(char *str,int first,int last) { assert(str!=NULL&&first<=last); int i=first,j=last; while(i<j) { str[i]=str[i]+str[j]; str[j]=str[i]-str[j]; str[i]=str[i]-str[j]; i++; j--; } } void RotateString(char *str,int n) //strcpy拷贝 { assert(str!=NULL&&n>=0); int len=strlen(str); char *strTemp=(char *)malloc(10);//需要 strcpy(strTemp,str+len-n); strcpy(strTemp+n,str); strTemp[len]=‘\0‘; strcpy(str,strTemp); free(strTemp); strTemp=NULL; } void RotateString1(char *str,int n) //库函数拷贝 { assert(str!=NULL&&n>=0); int len=strlen(str); char *temp=(char *)malloc(len+1); memcpy(temp,str+len-n,n); memcpy(temp+n,str,len-n); memcpy(str,temp,len); free(temp); } void RotateString2(char *str,int n)//三次翻转 { assert(str!=NULL&&n>0); int len=strlen(str); ReverseString(str,0,len-1); ReverseString(str,0,n-1); ReverseString(str,n,len-1); } int main() { char str[]="abcdef"; //RotateString(str,2); RotateString2(str,2); printf("%s\n",str); }
3、string类的编写
#include<iostream> #include<string.h> using namespace std; class MyString { public: MyString(const char *str); MyString(const MyString &other); ~MyString(); MyString & operator=(const MyString &stringA); void print() { cout<<m_str<<endl; } private: char *m_str; }; MyString::MyString(const char *str) { if(str==NULL) { m_str=new char [1]; m_str[0]=‘\0‘; } m_str=new char [strlen(str)+1]; strcpy(m_str,str); } MyString::MyString(const MyString &other) { int len=strlen(other.m_str); m_str=(char*)malloc(len+1); strcpy(m_str,other.m_str); } MyString::~MyString() { delete [] m_str; } MyString & MyString::operator=(const MyString &strA) { if(this==&strA) return *this; delete[] m_str; int len=strlen(strA.m_str); m_str=new char[len+1]; strcpy(m_str,strA.m_str); return *this; } void main() { char string1[]="abcd"; char string2[]="efgh"; MyString str1(string1); str1.print(); MyString str2(string2); str2=str1; str2.print(); }
20140902 字符串拷贝函数 右旋转字符串 string类的编写
标签:des style blog color os io ar 2014 div
原文地址:http://www.cnblogs.com/yexuannan/p/3953620.html