我试图从字符数组切掉最后4个字符,我尝试了python使用的方法没有成功;
char *charone = (char*)("I need the last four")
char *chartwo = charone[-4:]
cout << chartwo << endl;
Run Code Online (Sandbox Code Playgroud)
我希望这段代码能够返回;
four
Run Code Online (Sandbox Code Playgroud)
但是c/c ++似乎并不那么容易......
我在哪里可以找到一个简单的替代方法,将一个char数组的最后4个字符返回到另一个char数组?
Jer*_*ock 14
尝试:
int len = strlen(charone);
char *chartwo = charone + (len < 4 ? 0 : len - 4);
Run Code Online (Sandbox Code Playgroud)
在C++中,您可以将其替换为:
char* chartwo = charone + (std::max)(strlen(charone), 4) - 4;
Run Code Online (Sandbox Code Playgroud)
该代码使用C字符串的特殊属性,该属性仅用于切断字符串的开头.
首先,让我们删除不推荐的转换:
char const *charone = "I need the last four";
Run Code Online (Sandbox Code Playgroud)
数组不是C++中的第一类值,它们不支持切片.但是,正如上面的charone指向数组中的第一项,您可以指向任何其他项.指针与字符一起用于制作C风格的字符串:指向字符串,直到空字符串为字符串的内容.因为您想要的字符位于当前(charone)字符串的末尾,所以您可以指向"f":
char const *chartwo = charone + 16;
Run Code Online (Sandbox Code Playgroud)
或者,处理任意字符串值:
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;
Run Code Online (Sandbox Code Playgroud)
或者,因为您正在使用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".
Run Code Online (Sandbox Code Playgroud)
特别要注意的是,std :: string为您提供了不同的值,因此修改任一字符串都不会像指针那样修改另一个字符串.