2011-02-19 888 views
8

我想切掉字符数组中的最后4个字符,我尝试了python使用没有成功的方法;在c + +中的数组切片

char *charone = (char*)("I need the last four") 
char *chartwo = charone[-4:] 

cout << chartwo << endl; 

我想要这段代码返回;

four 

但C/C++似乎不那么容易......

我在哪里能找到一个简单的替代方案,将在最后4个字符一个字符数组的返回到另一个字符数组?

+0

你为什么投?是因为你使用的是gcc,它会给出警告? – 2011-02-19 02:16:43

+0

是的XP,当我没有,我通常会得到一个分段错误。 – MetaDark 2011-02-19 02:23:05

+1

对,在C++中,字符串文字是const char,所以你应该使用一个const char *来指向它。这也许是编译器告诉你的。 – 2011-02-19 10:51:16

回答

12

尝试:

int len = strlen(charone); 
char *chartwo = charone + (len < 4 ? 0 : len - 4); 

在C++中,你可以用替换:

char* chartwo = charone + (std::max)(strlen(charone), 4) - 4; 

的代码使用C字符串的特殊属性,仅适用于斩去一个字符串的开头。

1

这将做到这一点:

char* chartwo = charone + 16; 
7

首先,让我们删除过时的转换:

char const *charone = "I need the last four"; 

数组是不是在C++一流的价值,他们不支持片断。但是,正如上面的charone指向数组中的第一个项目,您可以指向任何其他项目。指针与chars一起使用来创建C风格的字符串:指向字符的字符,直到空字符为字符串的内容为止。因为你想要的字符是在当前(charone)字符串的结尾,你可以在“F”指出:

char const *chartwo = charone + 16; 

或者,处理任意字符串值:

char const *charone = "from this arbitrary string value, I need the last four"; 
int charone_len = strlen(charone); 
assert(charone_len >= 4); // Or other error-checking. 
char const *chartwo = charone + charone_len - 4; 

或者,因为您使用C++:

std::string one = "from this arbitrary string value, I need the last four"; 
assert(one.size() >= 4); // Or other error-checking, since one.size() - 4 
// might underflow (size_type is unsigned). 
std::string two = one.substr(one.size() - 4); 

// To mimic Python's [-4:] meaning "up to the last four": 
std::string three = one.substr(one.size() < 4 ? 0 : one.size() - 4); 
// E.g. if one == "ab", then three == "ab". 

尤其注意的std :: string给你不同值,所以无论是修改字符串不修改其他如发生s用指针。

3

如果你正在寻找只是短暂访问的最后四个字符,然后像

char* chartwo = charone + (strlen(charone) - 4); 

将被罚款(加上一些错误检查)。

但是,如果你要复制的蟒蛇功能,则需要副本最后四个字符。再次,使用strlen获取长度(或将其存储在某个地方),然后使用strcpy(或者可能是一个更好的具有相同功能的stl函数)。像...

char chartwo[5]; 
strcpy(chartwo, charone + strlen(charone) - 4); 

(注:如果你不复制,那么你就不能免费charone直到您使用完chartwo。另外,如果你不复制,那么如果你稍后改变charone,那么chartwo也会改变。如果没关系,那么肯定只是指向偏移量。)

1

阵列在C++切片:

array<char, 13> msg = {"Hello world!"}; 
array<char, 6> part = {"world"}; 

// this line generates no instructions and does not copy data 
// It just tells the compiler how to interpret the bits 
array<char, 5>& myslice = *reinterpret_cast<array<char,5>*>(&msg[6]); 

// now they are the same length and we can compare them 
if(myslice == part) 
    cout<< "huzzah"; 

这仅仅是其中的切片是有用的emamples之一

我已经作出了小库,执行此编译时在https://github.com/Erikvv/array-slicing-cpp

边界检查