The Wayback Machine - https://web.archive.org/web/20240826142515/https://www.geeksforgeeks.org/how-to-split-a-string-in-cc-python-and-java/
Open In App

How to split a string in C/C++, Python and Java?

Last Updated : 13 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Solve Problem
Basic
52.61%
16.2K

Splitting a string by some delimiter is a very common task. For example, we have a comma-separated list of items from a file and we want individual items in an array. 
Almost all programming languages, provide a function split a string by some delimiter. 


In C:  

// Splits str[] according to given delimiters.
// and returns next token. It needs to be called
// in a loop to get all tokens. It returns NULL
// when there are no more tokens.
char * strtok(char str[], const char *delims);
C
// A C/C++ program for splitting a string
// using strtok()
#include <stdio.h>
#include <string.h>

int main()
{
    char str[] = "Geeks-for-Geeks";

    // Returns first token 
    char *token = strtok(str, "-");
  
    // Keep printing tokens while one of the
    // delimiters present in str[].
    while (token != NULL)
    {
        printf("%s\n", token);
        token = strtok(NULL, "-");
    }

    return 0;
}
Output: Geeks
for
Geeks

Time complexity : O(n)

Auxiliary Space: O(n)

In C++

Note:  The main disadvantage of strtok() is that it only works for C style strings.
Therefore we need to explicitly convert C++ string into a char array.
Many programmers are unaware that C++ has two additional APIs which are more elegant
and works with C++ string.

Method 1: Using  stringstream API of C++

Prerequisite:  stringstream API 

Stringstream object can be initialized using a string object, it automatically tokenizes strings on space char. Just like “cin” stream stringstream allows you to read a string as a stream of words. Alternately, we can also utilise getline function to tokenize string on any single character delimiter.

Some of the Most Common used functions of StringStream.
clear() — flushes the stream
str() — converts a stream of words into a C++ string object.
operator << — pushes a string object into the stream.
operator >> — extracts a word from the stream.

 The code below demonstrates it. 

C++
#include <bits/stdc++.h>
using namespace std;

// A quick way to split strings separated via spaces.
void simple_tokenizer(string s)
{
    stringstream ss(s);
    string word;
    while (ss >> word) {
        cout << word << endl;
    }
}

// A quick way to split strings separated via any character
// delimiter.
void adv_tokenizer(string s, char del)
{
    stringstream ss(s);
    string word;
    while (!ss.eof()) {
        getline(ss, word, del);
        cout << word << endl;
    }
}

int main(int argc, char const* argv[])
{
    string a = "How do you do!";
    string b = "How$do$you$do!";
    // Takes only space separated C++ strings.
    simple_tokenizer(a);
    cout << endl;
    adv_tokenizer(b, '$');
    cout << endl;
    return 0;
}
Output : How 
do
you
do!

Time Complexity: O(n)

Auxiliary Space:O(n)

Where n is the length of the input string.

Method 2: Using C++ find() and substr() APIs.

Prerequisite: find function and substr().

This method is more robust and can parse a string with any delimiter, not just spaces(though the default behavior is to separate on spaces.) The logic is pretty simple to understand from the code below.

C++
#include <bits/stdc++.h>
using namespace std;

void tokenize(string s, string del = " ")
{
    int start, end = -1*del.size();
    do {
        start = end + del.size();
        end = s.find(del, start);
        cout << s.substr(start, end - start) << endl;
    } while (end != -1);
}
int main(int argc, char const* argv[])
{
    // Takes C++ string with any separator
    string a = "How$%do$%you$%do$%!";
    tokenize(a, "$%");
    cout << endl;

    return 0;
}
Output: How 
do
you
do
!

Time Complexity: O(n)

Auxiliary Space:O(1)

Where n is the length of the input string.

Method 3: Using  temporary string

If you are given that the length of the delimiter is 1, then you can simply use a temp string to split the string. This will save the function overhead time in the case of method 2.

C++
#include <iostream>
using namespace std;

void split(string str, char del){
    // declaring temp string to store the curr "word" upto del
      string temp = "";
  
      for(int i=0; i<(int)str.size(); i++){
        // If cur char is not del, then append it to the cur "word", otherwise
          // you have completed the word, print it, and start a new word.
         if(str[i] != del){
            temp += str[i];
        }
          else{
            cout << temp << " ";
              temp = "";
        }
    }
      
      cout << temp;
}

int main() {

    string str = "geeks_for_geeks";    // string to be split
     char del = '_';    // delimiter around which string is to be split
  
      split(str, del);
    
    return 0;
}

Output
geeks for geeks

Time complexity : O(n)

Auxiliary Space: O(n)

In Java : 
In Java, split() is a method in String class. 

// expregexp is the delimiting regular expression; 
// limit is the number of returned strings
public String[] split(String regexp, int limit);

// We can call split() without limit also
public String[] split(String regexp)
Java
// A Java program for splitting a string
// using split()
import java.io.*;
public class Test
{
    public static void main(String args[])
    {
        String Str = new String("Geeks-for-Geeks");

        // Split above string in at-most two strings  
        for (String val: Str.split("-", 2))
            System.out.println(val);

        System.out.println("");
  
        // Splits Str into all possible tokens 
        for (String val: Str.split("-"))
            System.out.println(val);
    }
}

Output: 

Geeks
for-Geeks

Geeks
for
Geeks

Time complexity : O(n)
Auxiliary Space: O(1)

In Python: 
The split() method in Python returns a list of strings after breaking the given string by the specified separator.  

 
// regexp is the delimiting regular expression;
// limit is limit the number of splits to be made
str.split(regexp = "", limit = string.count(str))
Python
line = "Geek1 \nGeek2 \nGeek3"
print(line.split())
print(line.split(' ', 1))

Output: 

['Geek1', 'Geek2', 'Geek3']
['Geek1', '\nGeek2 \nGeek3']

Time Complexity : O(N), since it just traverse through the string finding all whitespace.

Auxiliary Space : O(1), since no extra space has been used.

This article is contributed by Aarti_Rathi and Aditya Chatterjee.


How to split a string in C/C++, Python and Java? – FAQs

How to Split a String by C++? 

In C++, there isn’t a built-in split function like in higher-level languages such as Python, but you can achieve string splitting using several techniques such as using istringstream from the <sstream> header. This method is useful for splitting strings based on whitespace or specified delimiters:

#include <iostream>
#include <sstream>
#include <vector>
#include <string>

std::vector<std::string> split_string(const std::string &str, char delim = ' ') {
std::vector<std::string> tokens;
std::stringstream ss(str);
std::string token;
while (getline(ss, token, delim)) {
if (!token.empty())
tokens.push_back(token);
}
return tokens;
}

int main() {
std::string str = "Split this string";
std::vector<std::string> tokens = split_string(str);
for (const auto &t : tokens) {
std::cout << t << std::endl;
}
return 0;
}

How Do You Break a String into Multiple Lines in C++?

To break a string into multiple lines in C++, you can use string literals separated by newlines (\n), or you can continue the string on a new line using the line continuation character (\):

#include <iostream>

int main() {
std::string str = "This is a very long string "
"that needs to be broken into "
"multiple lines for readability.";
std::cout << str << std::endl;
return 0;
}

How Do You Extract Part of a String in C++?

To extract a part of a string in C++, you can use the substr() method, which takes the starting index and the length of the substring as parameters:

#include <iostream>
#include <string>

int main() {
std::string str = "Hello, world!";
std::string part = str.substr(7, 5); // Start at index 7, length 5
std::cout << part << std::endl; // Outputs "world"
return 0;
}

What is Slicing in Python?

Slicing in Python is a method to extract parts of lists, strings, or any other sequence type, based on start and end indices. You can specify a slice using the colon (:) operator:

s = "Hello, world!"
part = s[7:12] # Get the substring from index 7 to 11
print(part) # Outputs "world"

How to Take Multi Word String in C++?

To take a multi-word string from user input in C++, you can use getline() from the <iostream> library, which reads an entire line from the standard input (std::cin), including spaces:

#include <iostream>
#include <string>

int main() {
std::string line;
std::cout << "Enter a string: ";
std::getline(std::cin, line);
std::cout << "You entered: " << line << std::endl;
return 0;
}

These methods in C++ handle common tasks related to string manipulation, mimicking some of the functionality found in higher-level languages and providing a solid foundation for more complex text processing tasks



Similar Reads

Python | Pandas Split strings into two List/Columns using str.split()
Pandas provide a method to split string around a passed separator/delimiter. After that, the string can be stored as a list in a series or it can also be used to create multiple column data frames from a single separated string. It works similarly to Python's default split() method but it can only be applied to an individual string. Pandas &lt;code
4 min read
Minimum length of a rod that can be split into N equal parts that can further be split into given number of equal parts
Given an array arr[] consisting of N positive integers, the task is to find the minimum possible length of a rod that can be cut into N equal parts such that every ith part can be cut into arr[i] equal parts. Examples: Input: arr[] = {1, 2}Output: 4Explanation:Consider the length of the rod as 4. Then it can be divided in 2 equal parts, each having
7 min read
Split the string into minimum parts such that each part is in the another string
Given two strings A and B, the task is to split the string A into the minimum number of substrings such that each substring is in the string B. Note: If there is no way to split the string, then print -1 Examples: Input: A = "abcdab", B = "dabc" Output: 2 Explanation: The two substrings of A which is also present in B are - {"abc", "dab"} Input: A
11 min read
Split() String method in Java with examples
The string split() method breaks a given string around matches of the given regular expression. After splitting against the given regular expression, this method returns a string array. Input String: 016-78967Regular Expression: - Output : {"016", "78967"}Following are the two variants of the split() method in Java: 1. Public String [] split ( Stri
5 min read
Split and Parse a string in Python
In Python, working with strings is a fundamental aspect of programming. Strings are sequences of characters and often contain structured data that needs to be processed or analyzed. The common operations performed on strings are splitting and parsing. Splitting a String in PythonIn Python, you can split a string into smaller parts using the split()
5 min read
Split a string in equal parts (grouper in Python)
Grouper recipe is an extended toolset made using an existing itertool as building blocks. It collects data into fixed-length chunks or blocks. Existing Itertools Used: izip_longest(*iterables[, fillvalue]) : Make an iterator that aggregates elements from each of the iterables. If the iterables are of uneven length, missing values are filled-in with
2 min read
Python | Split multiple characters from string
In Python, Strings are a basic data type that is used to store and work with textual data. Splitting a string into numerous characters is a frequent text-processing activity in Python. While coding or improvising your programming skill, you surely must have come across many scenarios where you wished to use split() in Python not to split on only on
5 min read
Python String split()
Python String split() method splits a string into a list of strings after breaking the given string by the specified separator. Example: [GFGTABS] Python string = &quot;one,two,three&quot; words = string.split(&#39;,&#39;) print(words) [/GFGTABS]Output: ['one', 'two', 'three']Python String split() Method SyntaxSyntax: str.split(separator, maxsplit)
6 min read
Split a Binary String such that count of 0s and 1s in left and right substrings is maximum
Given a binary string, str of length N, the task is to find the maximum sum of the count of 0s on the left substring and count of 1s on the right substring possible by splitting the binary string into two non-empty substrings. Examples: Input: str = "000111" Output: 6 Explanation: Splitting the binary string into "000" and "111". Count of 0s in the
7 min read
Split a binary string into K subsets minimizing sum of products of occurrences of 0 and 1
Given a binary string S, the task is to partition the sequence into K non-empty subsets such that the sum of products of occurrences of 0 and 1 for all subsets is minimum. If impossible print -1.Examples: Input: S = "0001", K = 2 Output: 0 Explanation We have 3 choices {0, 001}, {00, 01}, {000, 1} The respective sum of products are {1*0 + 2*1 = 2},
8 min read
Split numeric, alphabetic and special symbols from a String
Given string str, divide the string into three parts one containing a numeric part, one containing alphabetic, and one containing special characters. Examples: Input : geeks01for02geeks03!!! Output :geeksforgeeks 010203 !!! Here str = "Geeks01for02Geeks03!!!", we scan every character and append in res1, res2 and res3 string accordingly. Input : **D
3 min read
Split the binary string into substrings with equal number of 0s and 1s
Given a binary string str of length N, the task is to find the maximum count of consecutive substrings str can be divided into such that all the substrings are balanced i.e. they have equal number of 0s and 1s. If it is not possible to split str satisfying the conditions then print -1.Example: Input: str = "0100110101" Output: 4 The required substr
8 min read
Count ways to split string into K Substrings starting with even digit and min length M
Given a string S of length N consisting of digits from '0' to '9' .The task is to determine the total number of possible ways to partition the string into K substrings such that : Each substring has a minimum length of M (M&gt;=2).Substring must start with an even digit number and end with an odd digit number.Examples: Input: N = 9, M = 2, k = 3, S
15+ min read
Difference Between StringTokenizer and Split Method in Java
Legacy classes and interfaces are the classes and interfaces that formed the Collection Framework in the earlier versions of Java and how now been restructured or re-engineered. Splitting of String is basically breaking the string around matches of the given regular expression. Strings can be split in many ways in java but the 2 most common ways ar
3 min read
Split the string into substrings using delimiter
Given a string and a delimiter character. Split the string based on the delimiter and print the list of resulting sub strings. Examples: Input : str = "geeks;for;geeks" d_ch = ';' Output : geeks for geeks Input : str = "##ayush##jauhari####" d_ch = '#' Output : ayush jauhari Source: Microsoft IDC Bangalore Interview | Set 153 Algorithm: splitString
6 min read
Split a String into two Substring such that the sum of unique characters is maximum
Given a string str, the task is to partition the string into two substrings such that the sum of unique characters of both substrings is the maximum possible. Examples: Input: str = "abcabcd” Output: 7Explanation: Partition the given string into "abc" and "abcd", the sum of unique characters is 3 + 4 = 7 which is maximum possible. Input: str = "aaa
14 min read
numpy string operations | split() function
numpy.core.defchararray.split(arr, sep=None, maxsplit=None) is another function for doing string operations in numpy.It returns a list of the words in the string, using sep as the delimiter string for each element in arr. Parameters: arr : array_like of str or unicode.Input array. sep : [ str or unicode, optional] specifies the separator to use whe
2 min read
Split the given string into Primes : Digit DP
Given a string str that represents a large number, the task is to find the minimum number of segments the given string can be divided such that each segment is a prime number in the range of 1 to 106. Examples: Input: str = "13499315" Output: 3 Explanation: The number can be segmented as [13499, 31, 5] Input: str = "43" Output: 1 Explanation: The n
15+ min read
Split the given string into Odds: Digit DP
Prerequisites: Digit-DP Given string str that represents a large number, the task is to find the minimum number of segments the given string can be divided such that each segment is an odd number in the range of 1 to 109.Examples: Input: str = "123456789123456789123" Output: 3 Explanation: The number can be divided as {123456789, 123456789, 123}Inp
9 min read
Remove minimum characters from string to split it into three substrings under given constraints
Given a string str of lowercase alphabets, the task is to remove minimum characters from the given string so that string can be break into 3 substrings str1, str2, and str3 such that each substring can be empty or can contains only characters 'a', 'b', and 'c' respectively.Example: Input: str = "aaaabaaxccac" Output: 3 Explanation: String after rem
8 min read
Count of ways to split given string into two non-empty palindromes
Given a string S, the task is to find the number of ways to split the given string S into two non-empty palindromic strings.Examples: Input: S = "aaaaa" Output: 4 Explanation: Possible Splits: {"a", "aaaa"}, {"aa", "aaa"}, {"aaa", "aa"}, {"aaaa", "a"}Input: S = "abacc" Output: 1 Explanation: Only possible split is "aba", "cc". Recommended: Please t
15+ min read
Check if a string can be split into two strings with same number of K-frequent characters
Given a string S and an integer K, the task is to check if it is possible to distribute these characters into two strings such that the count of characters having a frequency K in both strings is equal. If it is possible, then print a sequence consisting of 1 and 2, which denotes which character should be placed in which string. Otherwise, print NO
11 min read
Check if a string can be split into even length palindromic substrings
Given a string str, the task is to check if it is possible to split the given string into even length palindromic substrings. Examples: Input: str = "abbacc" Output: Yes Explanation: Strings "abba" and "cc" are the even length palindromic substrings.Input: str = "abcde" Output: No Explanation: No even length palindromic substrings possible. Approac
6 min read
Check if a string can be split into substrings starting with N followed by N characters
Given a string str, the task is to check if it can be split into substrings such that each substring starts with a numeric value followed by a number of characters represented by that numeric integer. Examples: Input: str = "4g12y6hunter" Output: Yes Explanation: Substrings "4g12y" and "6hunter" satisfy the given condition Input: str = "31ba2a" Out
5 min read
Count ways to split a Binary String into three substrings having equal count of zeros
Given binary string str, the task is to count the total number of ways to split the given string into three non-overlapping substrings having the same number of 0s. Examples: Input: str = "01010" Output: 4 Explanation: The possible splits are: [0, 10, 10], [01, 01, 0], [01, 0, 10], [0, 101, 0] Input: str = "11111" Output: 0 Approach: To solve the p
15+ min read
Check if a palindromic string can be obtained by concatenating substrings split from same indices of two given strings
Given two strings A and B of length N, the task is to check if any of the two strings formed by splitting both the strings at any index i (0 ≤ i ≤ N - 1) and concatenating A[0, i] and B[i, N - 1] or A[i, N - 1] and B[0, i] respectively, form a palindromic string or not. If found to be true, print "Yes". Otherwise, print "No". Examples: Input: A = "
15+ min read
Check if a string can be split into 3 substrings such that one of them is a substring of the other two
Given a string S consisting of N lowercase alphabets, the task is to check if it is possible to split the string S into three non-empty substrings such that Y is the substring of the strings X and Z. If it is possible to split the string S then, print "Yes". Otherwise, print "No". Examples: Input: S = "geekseekforgeeks"Output: YesExplanation:The gi
5 min read
Check if a string can be split into two substrings such that one substring is a substring of the other
Given a string S of length N, the task is to check if a string can be split into two substrings, say A and B such that B is a substring of A. If not possible, print No. Otherwise, print Yes. Examples : Input: S = "abcdab"Output: YesExplanation: Considering the two splits to be A="abcd" and B="ab", B is a substring of A. Input: S = "abcd"Output: No
5 min read
Split a string into maximum number of unique substrings
Given string str, the task is to split the string into the maximum number of unique substrings possible and print their count. Examples: Input: str = "ababccc"Output: 5Explanation:Split the given string into the substrings "a", "b", "ab", "c" and "cc".Therefore, the maximum count of unique substrings is 5. Input: str = "aba"Output: 2 Approach: The
6 min read
Check if a Binary String can be split into disjoint subsequences which are equal to "010"
Given a binary string, S of size N, the task is to check if it is possible to partition the string into disjoint subsequences equal to "010". Examples: Input: S = "010100"Output: YesExplanation: Partitioning the string in the manner 010100 to generate two subsequences equal to "010". Input: S = "010000"Output: No Approach: The idea is based on the
8 min read