1. strncpy string copy Function
// Strncpy Program # 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 -- it must be placed in front. When n = 0 is detected in the exit loop, the next judgment condition will not be done. * (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. Right-rotating string
// 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) // copy {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) // copy the library function {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) // trigger {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. Write the string class
#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 compiling of string copying function right-rotating string class