版权声明:QQ:763905926 未经允许请勿转载,转载请注明出处! https://blog.csdn.net/lms1008611/article/details/87623019
今天来实现一个基础算法:判断一个字符串是否对称。例如 char str[] = "abcdcba",这样的字符串便是对称的。实现很简单,主要是指针操作即可,下边直接上代码
//头文件
#ifndef __LMSPUBLICLIB_H__
#define __LMSPUBLICLIB_H__
#include <stdio.h>
#include <unistd.h>
#include <string>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <assert.h>
#include <vector>
using namespace std;
#ifndef MAX_PATH
#define MAX_PATH 256
#endif
#ifdef WIN32
#define DIR_SLITTER '\\'
#else
#define DIR_SPLITTER '/'
#endif
namespace LmsPublicLib
{
bool SmpStr(const char* str);
};
#endif //__LMSPUBLICLIB_H__
//源文件
#include "LmsPublicLib.h"
namespace LmsPublicLib
{
bool SmpStr(const char* str)
{
if(!str)
{
return false;
}
bool isSmp = false;
char szBuf[MAX_PATH] = {0};
strcpy(szBuf, str);
szBuf[strlen(szBuf)] = '\0';
char *pHead = szBuf;
char *pTail = szBuf + strlen(szBuf) -1;
while( (pTail - pHead) > 0)
{
if(*(pHead++) != *(pTail--))
{
isSmp = false;
break;
}
isSmp = true;
}
return isSmp;
}
}
//main.cpp测试文件
#include "LmsPublicLib.h"
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
char str[256] = "abcdcba";
bool ret = LmsPublicLib::SmpStr(str);
cout << "SmpStr ret = " << ret << endl;
return 0;
}
编译执行一下: