It took more than an hour to finish writing and post it to share it with you. It's all about string operations. If you don't understand it, please leave a message and note it clearly.
[Cpp]
# Include <stdio. h>
/**
String operation & rewrite some string operation functions in C System
Strcpy strcmp strcat
*/
Void strReplace (char *, char *, int); // replace
Char * strCopy (char *, const char *); // copy
Int strCompare (char *, char *); // comparison
Char * strConcat (char *, char *); // concatenate
Void strConvert (char *); // Invert
Int strLength (char *); // get the length
// Call a function
Void strOperate ()
{
Char source [] = "China ";
Char rep [] = "ese ";
// Replace
Puts ("--------- replace ------------");
StrReplace (source, rep, 4 );
Puts (source );
// Copy
Puts ("--------- strcpy ------------");
Char distStr [10];
StrCopy (distStr, "abcdefg ");
Puts (distStr );
// Compare
Puts ("--------- strcmp ------------");
Printf ("% d \ n", strCompare ("ABCD", "ABC "));
// Obtain the length
Puts ("--------- strlength ------------");
Printf ("% d \ n", strLength ("ABCDe "));
// Splicing
Puts ("--------- strconcat ------------");
Char SC [30] = "Chinese ";
StrConcat (SC, "FUCK Japanese ");
Puts (SC );
// Invert
Puts ("--------- strconvert ------------");
Char s [] = "I love my homeland ";
StrConvert (s );
Puts (s );
}
// Replace www.2cto.com
Void strReplace (char * soucrStr, char * replaceStr, int pos)
{
While (pos> 0 & * soucrStr! = '\ 0') // pos> 1 to prevent pointer moving behind, so it is not accurate
{
SoucrStr ++; // move the pointer to the specified position
Pos --;
}
While (* soucrStr! = '\ 0' & * replaceStr! = '\ 0 ')
{
* SoucrStr = * replaceStr; // replace
SoucrStr ++;
ReplaceStr ++;
}
}
// Copy (the target character array is larger than the source array, otherwise it will overflow, resulting in various tragedies)
Char * strCopy (char * distStr, const char * sourceStr)
{
Char * address = distStr;
While (* distStr ++ = * sourceStr ++ )! = '\ 0'); // values are assigned first and then automatically added.
// * DistStr ++ is a pointer ++, which is then taken to the right to the left and tested separately.
Return address;
}
// Compare
Int strCompare (char * str1, char * str2)
{
While (* str1 & * str2 & (* str1 = * str2 ))
{
Str1 ++;
Str2 ++;
}
Return * str1-* str2;
}
// Splicing
Char * strConcat (char * distStr, char * sourceStr)
{
Char * address = distStr;
While (* distStr) // move to the end of the target string. If you use while (* distStr ++), an error occurs.
{
DistStr ++;
}
While (* distStr ++ = * sourceStr ++ )! = '\ 0 ');
Return address;
}
// Invert
Void strConvert (char * str)
{
Int len = strLength (str );
Int mid = len/2;
Char tmp;
For (int I = 0; I <mid; I ++)
{
Tmp = str [I];
Str [I] = str [len-i-1];
Str[ len-i-1] = tmp;
}
}
// Obtain the length
Int strLength (char * str)
{
Int len = 0;
While (* str ++)
Len ++;
Return len;
}
From mzlqh's column