C++ 删除字符后的所有内容(以及字符)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10392405/
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
Removing everything after character (and also character)
提问by James Harzs
I have a string like this:
我有一个这样的字符串:
std::string string1 = "xjdfhfakdjs%54k34k.-jk34";
I need to get only ""xjdfhfakdjs", but the string is dynamic, not hardcoded so I don't know what is it, the length etc. so I wanted to remove everything after %, and also the % char.
我只需要获得“xjdfhfakdjs”,但字符串是动态的,不是硬编码的,所以我不知道它是什么,长度等,所以我想删除 % 之后的所有内容,以及 % 字符。
How could I do this?
我怎么能这样做?
采纳答案by Shawn Johnson
I believe that will work.
我相信这会奏效。
std::string mystr = string1.substr(0, string1.find("%", 0));
回答by Edward Loper
std::string the_prefix_you_want = string1.substr(0, string1.find("%"));
See: http://www.cplusplus.com/reference/string/string/find/and http://www.cplusplus.com/reference/string/string/substr/for more details
有关更多详细信息,请参阅:http: //www.cplusplus.com/reference/string/string/find/和http://www.cplusplus.com/reference/string/string/substr/
回答by Laurie Stearn
Did a C-like thing which does work in its current form, but certainly more clunky than the methods shown above:
做了一个类似 C 的东西,它以当前的形式工作,但肯定比上面显示的方法更笨拙:
#include <windows.h>
void main ()
{
int i;
wchar_t searchString[100];
wchar_t * stringReturn;
memset(searchString, L'##代码##', sizeof(stringReturn));
wcscpy_s(searchString, 100, L"String\ to search");
stringReturn = wcschr (searchString, '\');
if (stringReturn)
{
for (i = 0; i < (int)(stringReturn - searchString); i++) stringReturn[i] = searchString[i];
stringReturn[i] = L'##代码##';
wcscpy_s(searchString, 100, stringReturn);
}
}
Can be easily modified to work for dynamic strings.
可以轻松修改以适用于动态字符串。