C + + string segmentation

Source: Internet
Author: User
Tags strtok

Both Java and C # can use split to split the string, but in C + + There is no such method, before always write a function of their own segmentation, not trouble, today on the Internet to find a similar function, found that Strtoc () seems to be able to complete the segmentation function of the string.

Prototype: Char *strtok (char s[], const char *delim);

Usage: decomposes a string into a set of strings. S is the character to be decomposed, and the Delim is a delimiter character (in the case of a string, the first is the split criterion). On first call, S points to the string to be decomposed, and then calls to set S to null. I don't quite understand why we should put s into null after that.

Using Strtok to achieve split
#include <iostream>
#include <string>
using namespace Std;
int main ()
{
String str= "ABC def,aaa *BBB";
const char *D = ", *";
Char *p;
p = strtok ((char *) str.c_str (), d);
while (p)
{
cout<<p<<endl;
P=strtok (NULL,D);
}

return 0;
}

It is important to note that strtok is a thread unsafe function because it uses statically allocated space to store the segmented string position.

C + + string segmentation

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.