C++中的字符串切片
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5048374/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
String slicing in C++
提问by MetaDark
I am trying to slice the last four characters off a character array, and I tried the method that Python uses without success;
我试图从字符数组中切出最后四个字符,我尝试了 Python 使用的方法但没有成功;
char *charone = (char*)("I need the last four")
char *chartwo = charone[-4:]
cout << chartwo << endl;
I would want this code to return:
我希望此代码返回:
four
But C/C++ doesn't seem to be that easy...
但是 C/C++ 似乎并没有那么容易......
Where could I find a simple alternative that will return the last four characters of one character array into another character array?
我在哪里可以找到一个简单的替代方法,它将一个字符数组的最后四个字符返回到另一个字符数组?
回答by Jeremiah Willcock
Try:
尝试:
int len = strlen(charone);
char *chartwo = charone + (len < 4 ? 0 : len - 4);
In C++, you can replace that with:
在 C++ 中,您可以将其替换为:
char* chartwo = charone + (std::max)(strlen(charone), 4) - 4;
The code uses a special property of C strings that only works for chopping off the beginning of a string.
该代码使用 C 字符串的一个特殊属性,该属性仅适用于切掉字符串的开头。
回答by Fred Nurk
First, let's remove the deprecated conversion:
首先,让我们删除已弃用的转换:
char const *charone = "I need the last four";
Arrays are not first-class values in C++, and they don't support slicing. However, just as the above charone points to the first item in the array, you can point to any other item. Pointers are used with chars to make C-style strings: the pointed-to char up until a null char is the contents of the string. Because the characters you want are at the end of the current (charone) string, you can point at the "f":
数组不是 C++ 中的一等值,并且它们不支持切片。但是,就像上面的 charone 指向数组中的第一项一样,您也可以指向任何其他项。指针与字符一起使用来创建 C 风格的字符串:指向的字符直到空字符是字符串的内容。因为你想要的字符在当前(charone)字符串的末尾,你可以指向“f”:
char const *chartwo = charone + 16;
Or, to handle arbitrary string values:
或者,处理任意字符串值:
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;
Or, because you're using C++:
或者,因为您使用的是 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".
In particular, note that std::string gives you distinctvalues, so modifying either string doesn't modify the other as happens with pointers.
特别要注意的是 std::string 为您提供了不同的值,因此修改任一字符串不会像指针那样修改另一个字符串。
回答by Nikolai Fetissov
C++ and Python are very different. C++ does not have built-in Python-like string facilities, but its Standard Template Libraryhas a handy std::string
type, which you should look into.
C++ 和 Python 是非常不同的。C++ 没有内置的类似 Python 的字符串工具,但它的标准模板库有一个方便的std::string
类型,你应该研究一下。
回答by jmilloy
If you are looking to just briefly access the last four characters, then something like
如果您只想简单地访问最后四个字符,那么类似于
char* chartwo = charone + (strlen(charone) - 4);
will be fine (plus some error checking).
会很好(加上一些错误检查)。
But if you want to replicate the python functionality, you will need to copythe last four characters. Again, use strlen to get the length (or store it somewhere beforehand), and then use strcpy(or probably a better stl function that has the same function). something like...
但是如果要复制 python 功能,则需要复制最后四个字符。同样,使用 strlen 获取长度(或预先将其存储在某处),然后使用strcpy(或可能具有相同功能的更好的 stl 函数)。就像是...
char chartwo[5];
strcpy(chartwo, charone + strlen(charone) - 4);
(Note: If you don't copy, then you can't free charone until you are finished using chartwo. Also, If you don't copy, then if you change charone later, chartwo will change as well. If that's okay, then sure, just point to the offset.)
(注意:如果你不复制,那么在你用完charone之前你不能释放charone。另外,如果你不复制,那么如果你以后改变charone,charone也会改变。如果没关系,那么当然,只需指向偏移量即可。)
回答by Chris Jester-Young
This will do it:
这将做到:
char* chartwo = charone + 16;
回答by Erik van Velzen
array slicing in c++:
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";
This is just one of the emamples where slicing is usefull
这只是切片有用的示例之一
I have made a small library which does this with compile-time bounds checks at https://github.com/Erikvv/array-slicing-cpp
我在https://github.com/Erikvv/array-slicing-cpp 上做了一个小库,它通过编译时边界检查来做到这一点