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

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 function split a string by some delimiter.

In C/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);
filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Output:

Geeks
for
Geeks



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)
 
filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);
    }
}

chevron_right


Output:

Geeks
for-Geeks

Geeks
for
Geeks



In Python:

 
  // regexp is the delimiting regular expression; 
  // limit is limit the number of splits to be made 
  str.split(regexp = "", limit = string.count(str)) 
filter_none

edit
close

play_arrow

link
brightness_4
code

line = "Geek1 \nGeek2 \nGeek3";
print line.split()
print line.split(' ', 1)

chevron_right


Output:

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

This article is contributed by Aditya Chatterjee. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above



My Personal Notes arrow_drop_up