How to use strtok() Method In C++
The strtok() method is used in C/C++ to tokenize a string. It takes two parameters, the first is a pointer to the string to be tokenized, and the second is a pointer to a set of delimiting characters. The method then returns a pointer to the token found in the string, which can then be used to copy it.
Syntax
char *strtok(char *str, const char *delim);\
Example: Program to copy the string using strtok() method
C++
// CPP program to copy the string // using strtok() method #include <cstring> #include <iostream> using namespace std; int main() { char str[] = "w3wiki GFG GEEKS" ; char * token = strtok (str, " " ); // token now contains the first word in the string char word[100]; strcpy (word, token); // word now contains a copy of the first word in the // string cout << word << endl; return 0; } // This code is contributed by Susobhan Akhuli |
w3wiki
Complexity Analysis
- Time Complexity: O(N)
- Auxiliary Space: O(1)
Note: In all the above methods the size of the destination array must be greater than the length of the source string to copy all the characters.
Different ways to copy a string in C/C++
Copying a string is a common operation in C/C++ used to create a duplicate copy of the original string. In this article, we will see how to copy strings in C/C++.