Python的切片功能很香,本篇实现在c++的字符串(用字符指针代表)上模仿python的切片功能。
在头文件stringFunctions.h中实现切片函数sliced:
#ifndef STRINGFUNCTIONS_H_INCLUDED
#define STRINGFUNCTIONS_H_INCLUDED
#include <exception>
using namespace std;
int len(char* s);
int convert(int index, int length);
char * sliced(char*s, int start, int end, int step =1);//默认参数写在函数声明中
char * nothing();
int len(char* s)
{
//计算字符串中字符个数(到'\0'为止,不含'\0')
int n_s = 0;
char *s1 = s;
while(*(s1++) != '\0') n_s++;
return n_s;
}
int convert(int index, int length)
{
//索引转换,将负数或者越界的索引转换到0 ~ length 区间
if (index <= -length) return 0;
else if (index < 0) return length + index;
else if(index < length) return index;
else return length;
}
char * nothing()
{
//生成指向空字符串的字符指针
char* c = new char[1];
*c ='\0';
return c;
}
char * sliced(char*s, int start, int end, int step)
{
// s 代表原字符串,start和end代表切片的起始和结束位置,step代表步长
if (step>0)
{
int leng, start_, end_, n_sliced, r ;
leng = len(s);
start_ = convert(start, leng);
end_ = convert(end, leng);
if(start_ >= end_) return nothing();
r = (end_ - start_) % step;
if(r==0) n_sliced = (end_ - start_)/ step;
else n_sliced = (end_ - start_)/ step + 1;
char* sliced= new char[n_sliced+1];
int i, index;
for(i=0; i<n_sliced; i++)
{
index = start_ + i * step;
sliced[i] = s[index];
}
sliced[i] = '\0';
return sliced;
}
else if (step<0)
{
int leng, start_, end_, n_sliced, r ;
leng = len(s);
start_ = convert(start, leng);
end_ = convert(end, leng);
if (start_ == leng) start_--;
if(start_ <= end_) return nothing();
r = (start_ - end_) % (-step);
if(r==0) n_sliced = (start_ - end_) / (-step);
else n_sliced = (start_ - end_) / (-step) + 1;
char* sliced= new char[n_sliced+1];
int i, index;
for(i=0; i<n_sliced; i++)
{
index = start_ + i * step;
sliced[i] = s[index];
//cout << index<<";"<< sliced<<endl;
}
sliced[i] ='\0';
return sliced;
}
else throw invalid_argument("slice step cannot be zero");
}
#endif // STRINGFUNCTIONS_H_INCLUDED
在main函数中写测试案例:
用法完全对照python的切片功能,起始和结束位置可以越界,可以是负数,步长也可以是负数(代表反向排列),结束位置不计入结果。
#include <iostream>
#include "stringFunctions.h"
using namespace std;
int main()
{
char a[100] ="0123456789ABCDEF";
char *b = sliced(a,2,13);
cout << b <<endl;
delete b;
b = sliced(a,2,10,2);
cout << b <<endl;
delete b;
b = sliced(a,-20,18,1);
cout << b <<endl;
delete b;
b = sliced(a,8,0,-2);
cout << b <<endl;
delete b;
b = sliced(a,25,-7,-2);
cout << b <<endl;
delete b;
return 0;
}运行结果如下
