C/C++对char*字符串的操作
C/C++自写的字符串操作函数
//连接字符串
void Strcat(char *before, char *after);
//复制字符串
void Strcpy(char *newstr, const char *oldstr);
//获取字符串长度
size_t Getlenth(const char *str);
//转化为小写
void Strlwr(char *str);
//转化为大写
void Strupr(char *str);
//比较字符串是否相等
bool Strcmp(const char *str1, const char *str2);
//将字符串2插入字符串2的指定位置
void StrInsert(const char *str1, const char *str2, int point);
实现部分
#include <stdio.h>
#include <stdlib.h>
#include "teststring.hpp"
void Strcat(char *before, char *after)
{
while (*before != '\0')
{
before++;
}
while (*after != '\0')
{
*before = *after;
before++;
after++;
}
*before = '\0';
}
void Strcpy(char *newstr, const char *oldstr)
{
while (*oldstr != '\0')
{
*newstr = *oldstr;
newstr++;
oldstr++;
}
*newstr = '\0';
}
size_t Getlenth(const char *str)
{
size_t length = 0;
if (str != NULL)
{
while (*str != '\0')
{
length++;
str++;
}
}
return length;
}
//转化为小写
void Strlwr(char *str)
{
while (*str != '\0')
{
if (*str <= 'Z' && *str >= 'A')
{
*str -= 'A' - 'a';
}
str++;
}
}
//转化为大写
void Strupr(char *str)
{
while (*str != '\0')
{
if (*str <= 'z' && *str >= 'a')
{
*str -= 'a' - 'A';
}
str++;
}
}
//比较字符串是否相等
bool Strcmp(const char *str1, const char *str2)
{
if ((*str1 != '\0') && (*str2 != '\0'))
{
return true;
}
while ((*str1 != '\0') && (*str2 != '\0'))
{
if (*str1 - *str2 != 0)
{
return false;
}
}
return true;
}
//将字符串2插入字符串2的指定位置
void StrInsert(char *str1, char *str2, int point)
{
char *str1_buff = str1;
size_t str1length = Getlenth(str1);
size_t str2length = Getlenth(str2);
char *tempstr = new char[str1length + str2length];
char *tempstr_buff = tempstr;
for (int i = 0; i < point; i++)
{
*tempstr_buff = *str1_buff;
tempstr_buff++;
str1_buff++;
}
while (*str2 != '\0')
{
*tempstr_buff = *str2;
tempstr_buff++;
str2++;
}
while (*str1_buff != '\0')
{
*tempstr_buff = *str1_buff;
tempstr_buff++;
str1_buff++;
}
*tempstr_buff = '\0';
Strcpy(str1, tempstr);
delete tempstr;
}