怎么实现几个字符串常用函数,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
实现几个字符串常用函数,练习一下写代码。经常谢谢代码,使自己不要忘了如何写代码。
字符比较函数
字符串赋值函数
求字符串长度
字符串那倒置
字符串比较
字符串连接
// string.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <assert.h>
#include "string.h"
//字符交换函数
void charswap(char& ch2, char& ch3)
{
char ch = ch2;
ch2 = ch3;
ch3 = ch;
}
//求字符串长度
int stringlength(const char* sourstr)
{
const char *pstr = sourstr;
int length = 0;
while(*pstr++ != '\0')
{
length++;
}
return length;
}
//字符串那倒置
char* stringconvert(char* sourstr)
{
int length = stringlength(sourstr);
int loopnumber = length / 2;
int index = 0;
while(index < loopnumber)
{
charswap(*(sourstr + index), *(sourstr + length - index - 1));
index++;
}
return sourstr;
}
//字符串复制
char* stringcopy(char* deststr, const char* sourstr)
{
const char* pstr = sourstr;
int index = 0;
while(*pstr != '\0')
{
*(deststr + index) = *pstr++;
index++;
}
*(deststr + index) = '\0';
return deststr;
}
//字符串连接
char* stringcontact(char* deststr, const char* sourstr)
{
const char* pstr = sourstr;
int length = stringlength(deststr);
int index = 0;
while(*pstr != '\0')
{
*(deststr + length + index) = *pstr++;
index++;
}
*(deststr + length + index ) = '\0';
return deststr;
}
//字符串比较函数
int stringcompare(const char* deststr, const char* sourstr)
{
const char* pdest = deststr;
const char* psour = sourstr;
while(*pdest == *psour && *pdest != '\0')
{
pdest++;
psour++;
}
return *pdest - *psour;
}
int main(int argc, char* argv[])
{
char buff1[100];
char buff2[100];
stringcopy(buff1, "reqre12345");
stringcopy(buff2, "reqre1");
printf("%d\n", stringcompare(buff1, buff2));
getchar();
return 0;
}
看完上述内容,你们掌握怎么实现几个字符串常用函数的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://www.xuebuyuan.com/3258487.html