开发者

Spliting std::string and a character array into two halves (efficiently)

How can we split a std::string and a null terminated character array into two halves s开发者_StackOverflowuch that both have same length?

Please suggest an efficient method for the same.You may assume that the length of the original string/array is always an even number.

By efficiently I mean using less number of bytes in both the cases, since something using loops and buffer is not what I am looking for.


    std::string s = "string_split_example";
    std::string half = s.substr(0, s.length()/2);
    std::string otherHalf = s.substr(s.length()/2);

    cout << s.length() << " : " << s << endl;
    cout << half.length()  << " : " << half << endl;
    cout << otherHalf .length()  << " : " << otherHalf  << endl;

Output:

20 : string_split_example
10 : string_spl
10 : it_example

Online Demo : http://www.ideone.com/fmYrO


You've already received a C++ answer, but here's a C answer:

int len = strlen(strA);
char *strB = malloc(len/2+1);
strncpy(strB, strA+len/2, len/2+1);
strA[len/2] = '\0';

Obviously, this uses malloc() to allocate memory for the second string, which you will have to free() at some point.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜