Removing everything after character (and also character)

旧时模样 提交于 2019-12-05 17:13:35

问题


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.

How could I do this?


回答1:


std::string mystr = string1.substr(0, string1.find("%", 0));

I believe that will work.




回答2:


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




回答3:


Did a C-like thing which does work in its current form, but certainly more clunky than the methods shown above:

#include <windows.h>
void main ()
{
    int i;
    wchar_t searchString[100];
    wchar_t * stringReturn;
    memset(searchString, L'\0', 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'\0';
        wcscpy_s(searchString, 100, stringReturn);
    }
}

Can be easily modified to work for dynamic strings.



来源:https://stackoverflow.com/questions/10392405/removing-everything-after-character-and-also-character

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!