Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

My homework assignment is take a string and split it into pieces at every new line. I have no idea what to do! Please help!

Note: This is a question. Please do not take the question and/or answers seriously. More information here.


locked by Doorknob May 13 at 12:16

This question exists because it has historical significance, but it is not considered a good, on-topic question for this site, so please do not use it as evidence that you can ask similar questions here. This question and its answers are frozen and cannot be changed. More info: help center.

closed as off-topic by Doorknob May 12 at 12:22

  • This question does not appear to be about programming puzzles or code golf within the scope defined in the help center.
If this question can be reworded to fit the rules in the help center, please edit the question.

Is this a popularity-contest or code-golf? –  anustart Dec 30 '13 at 22:55
@user1981338, neither, read the wiki of the code-trolling tag. –  Turion Dec 31 '13 at 14:32
Here's a valuable resource I found regarding string splitting... I hope you find it useful! bit.ly/1dSklhO –  WallyWest Jan 8 at 7:49
Code-trolling is in the process of being removed, as per the official stance. This post recieved over 75% "delete" votes on the poll. It does have a large amount of votes on the question and the answers, but it is over 3 months old and no reputation will be lost. Therefore, I am closing this and will delete it in 24 hours. Note that since this is an outlier in that it has a large amount of votes, I'll be happy to undelete and lock given a convincing argument on meta. –  Doorknob May 12 at 12:22
@Doorknob, this is not a question to be deleted according to your accepted answer in the linked official stance. It has 44 answers and 21 votes, which is quite popular. As for the poll, I wasn't even aware of such a poll existing until now. I'm not going into spending time on writing another answer on meta pro code-trolling since it's obvious that exactly the meta-users are opposed to code-trolling whereas a sizeable part of codegolf users isn't. Closing this question is an excellent idea, but deleting it is in my opinion unnecessary and unhelpful. –  Turion May 12 at 12:54
show 2 more comments

44 Answers 44


My homework assignment is take a string and split it into pieces at every new line. I have no idea what to do! Please help!

Tricky problem for a beginning C programming class! First you have to understand a few basics about this complicated subject.

A string is a sequence made up of only characters. This means that in order for programmers to indicate an "invisible" thing (that isn't a space, which counts as a character), you have to use a special sequence of characters somehow to mean that invisible thing.

  • On Windows, the new line is a sequence of two characters in the string: backslash and n (or the string "\n")

  • On Linux or OS/X Macs, it is a sequence of four characters: backslash, n, backslash, and then r: (or "\n\r").

(Interesting historical note: on older Macintoshes it was a different sequence of four characters: "\r\n"... totally backwards from how Unix did things! History takes strange roads.)

It may seem that Linux is more wasteful than Windows, but it's actually a better idea to use a longer sequence. Because Windows uses such a short sequence the C language runtime cannot print out the actual letters \n without using special system calls. You can usually do it on Linux without a system call (it can even print \n\ or \n\q ... anything but \n\r). But since C is meant to be cross platform it enforces the lowest common-denominator. So you'll always be seeing \n in your book.

(Note: If you're wondering how we're talking about \n without getting newlines every time we do, StackOverflow is written almost entirely in HTML...not C. So it's a lot more modern. Many of these old aspects of C are being addressed by things you might have heard about, like CLANG and LLVM.)

But back to what we're working on. Let's imagine a string with three pieces and two newlines, like:


You can see the length of that string is 3 + 2 + 3 + 2 + 3 = 13. So you have to make a buffer of length 13 for it, and C programmers always add one to the size of their arrays to be safe. So make your buffer and copy the string into it:

/* REMEMBER: always add one to your array sizes in C, for safety! */
char buffer[14];
strcpy(buffer, "foo\nbaz\nbar");

Now what you have to do is look for that two-character pattern that represents the newline. You aren't allowed to look for just a backslash. Because C is used for string splitting quite a lot, it will give you an error if you try. You can see this if you try writing:

char pattern[2];
strcpy(pattern, "\");

(Note: There is a setting in the compiler for if you are writing a program that just looks for backslashes. But that's extremely uncommon; backslashes are very rarely used, which is why they were chosen for this purpose. We won't turn that switch on.)

So let's make the pattern we really want, like this:

char pattern[3];
strcpy(pattern, "\n");

When we want to compare two strings which are of a certain length, we use strncmp. It compares a certain number of characters of a potentially larger string, and tells you whether they match or not. So strncmp("\nA", "\nB", 2) returns 1 (true). This is even though the strings aren't entirely equal over the length of three... but because only two characters are needed to be.

So let's step through our buffer, one character at a time, looking for the two character match to our pattern. Each time we find a two-character sequence of a backslash followed by an n, we'll use the very special system call (or "syscall") putc to put out a special kind of character: ASCII code 10, to get a physical newline.

#include "stdio.h"
#include "string.h"

char buffer[14]; /* actual length 13 */
char pattern[3]; /* actual length 2 */
int i = 0;

int main(int argc, char* argv[]) {
    strcpy(buffer, "foo\nbar\nbaz");
    strcpy(pattern, "\n");

    while (i < strlen(buffer)) {
       if (1 == strncmp(buffer + i, pattern, 2)) {
           /* We matched a backslash char followed by n */
           /* Use syscall for output ASCII 10 */
           putc(10, stdout);
           /* bump index by 2 to skip both backslash and n */
           i += 2;
       } else {
           /* This position didn't match the pattern for a newline */
           /* Print character with printf */
           printf("%c", buffer[i]);
           /* bump index by 1 to go to next matchable position */
           i += 1;

    /* final newline and return 1 for success! */
    putc(10, stdout); 
    return 1;

The output of this program is the desired result...the string split!


\t is for \trolling...

Absolutely incorrect from the top to the bottom. Yet filled with plausible-sounding nonsense that has scrambled information like what's in the textbook or Wikipedia. Program logic appears transparent in the context of the misinformation, but is completely misleading. Even global variables and returning an error code, for good measure...


Of course, there's only one character in the C string representation of the two-character source literal sequence \n. But making a buffer larger is harmless, as long as strlen() is used to get the actual length to operate on.


We try to convince the reader that strncmp is a boolean operation that either matches (1) or doesn't (0). But it actually has three return values (-1 matching less, 0 for equal, 1 for matching greater). Our two character "pattern" being compared is not [\, n], but rather [\n, \0]...picking up the implicit null terminator. As that sequence slides through the string it will never be greater than a two-character sequence it's compared to...at best it will be zero if there is a terminating newline in the input string.


So all this does is loop through the string and print it one character at a time. The top branch never runs. (Though you could get it to if your string had lower-than \n codes in it, say tab...which could be used to mysteriously omit characters from the output :-P)

Return 1 for success. Glorious. –  Turion Dec 30 '13 at 18:29
Awsome to the max :) –  Johannes Jan 1 at 22:34
Damn this one is pure evil. –  Thom Wiggers Jan 4 at 12:05
add comment
  1. Grab a scissor and the string you want to split.
  2. Open the scissor.
  3. Put your string between the scissor blades.
  4. Close the scissor.

Congratulations! Your string should now be split. If not, repeat the steps until it is. If you have repeated the steps a couple of times and the string is till not split, try use a sharper scissor.

DISCLAIMER: I am not responsible for any damage applied to you during the process.

+1 Really good answer. –  Victor Dec 30 '13 at 8:24
I tried not working... –  rakeshNS Jan 1 at 7:17
I got "Exception: Unsafe operation. Do not run with scissors" –  Paul Jan 5 at 10:58
My rock crushed the scissors! D'oh! –  bobbel Apr 9 at 12:03
My scissors accidentally cut the instructions...Seg fault? –  David Wilkins Apr 11 at 14:03
add comment


I feel so bad that you were given such an obvious trick question as homework. A highly advanced language such as Python makes this a simple two liner:

s = "this\nis a\ntest\n"
print s

Please upvote and accept.

Try to do it in one line, for extra credits!!!1! –  Anony-Mousse Dec 29 '13 at 22:41
You're one vote ahead of me at the moment. But I will resist the urge to downvote. :-) Oddly, my solution is the same... just very obfuscated! –  Dr. Rebmu Jan 16 at 4:49
add comment


In C it's really easy:

#include <stdio.h>

#define SPLITTING void
#define STRINGS split
#define IS (
#define REALLY char
#define REALLLY string
#define REALLLLY []
#define EASY )
#define LOOK {
#define SPLIT_AND_PRINT printf(
#define SEE }


Call it like this:


Working example:

Why it's evil:

  • It relies on the printf function to split the strings
  • It's totally incomprehensible
  • It will confuse anyone who does not understand #define (and even those who do)
Wow!!! That's soooo evil....I want to vote twice!!!!!!!! –  Fabricio Araujo Jan 8 at 17:57
add comment

This can be done in a few lines of code by the following simple algorithm:

  1. Look for the first newline character in the string.
  2. Append the part up to the newline to a list.
  3. Remove the part up to the newline from the string.
  4. If the string is not empty, go to step 1.

However, this is wasteful. This is essentially a linear search algorithm, which has linear time complexity (O(n)). I'll let you in on a more advanced technique: binary search. Binary search is a lot more efficient than linear search: it has only logarithmic time complexity (O(log(n)). This means that if the search space is twice as big, the search time doesn't double, it only increases by a fixed amount!

The code for binary search is a bit more complicated, because it uses the advanced techniques of recursion and divide-and-conquer. But it's definitely worth it for the performance benefit. If you submit that, I expect you'll get extra credit.

The gist of the algorithm is this:

  • Cut the string in two.
  • With a recursive call, split the first half of the string.
  • With a recursive call, split the second half of the string.
  • Put the pieces from the first half together with the pieces from the second half, and voilà!

You didn't specify a language, so I wrote it in Python. In the real world, of course, people don't write in Python — use C or C++ (or even better, assembly language) for real performance. Don't worry if you don't understand what all the code is doing — this is definitely advanced stuff.

#!/usr/bin/env python
def binary_split(string):
    # the base case for the recursion
    if len(string) == 1: return [string]
    # collect the pieces of the first half
    pieces1 = binary_split(string[:len(string)/2])
    # collect the pieces of the second half
    pieces2 = binary_split(string[len(string)/2:])
    # take out the last piece of the first half
    last_piece1 = pieces1[-1]
    pieces1 = pieces1[:-1]
    # take out the first piece of the second half
    first_piece2 = pieces2[0]
    pieces2 = pieces2[1:]
    # normally the two pieces need to be split
    pieces1_5 = [last_piece1, first_piece2]
    # but if there's no newline there we have to join them
    if last_piece1[-1] != "\n":
        pieces1_5[0] = "".join(pieces1_5)
        pieces1_5[1:] = []
    # finished!!!
    return pieces1 + pieces1_5 + pieces2

import sys
string = sys.stdin.read()
print binary_split(string)

Of course all the statements about performance are bogus. The “simple” algorithm may be linear or quadratic depending on how you interpret it. The “advanced” algorithm is Θ(n×log(n)) (pretty close to linear in practice), but boy, is the multiplicative constant high due to the incessant list rebuilding (which the implementation goes somewhat out of its way to foster).

The Python style, the comment style, the statements about language choices and just about everything else in this post do not reflect my actual opinion or habits either.

add comment

Visual Basic

The IO monad has a function to do that!

Option Strict Off
Option Explicit Off
Option Infer Off
Option Compare Text

Module Module1
    Sub Main()
        Dim i = 0

        For Each line In split_into_lines(Console.In.ReadToEnd())
            i += 1
            Console.WriteLine("Line {0}: {1}", i, line)
    End Sub

    Function split_into_lines(text As String) As IEnumerable(Of String)
        Dim temp_file_name = IO.Path.GetTempFileName()
        IO.File.WriteAllText(temp_file_name, text)
        split_into_lines = IO.File.ReadLines(temp_file_name)
    End Function
End Module
Every VB introduction should be firmly founded in a solid understanding of monads! –  Christopher Creutzig Dec 28 '13 at 20:22
add comment


                                                                                                                                                                                                                      #declare private public
#include <strstream>
using namespace std;

void f(std::string &a, char **b) {
  strstream *c = new ((strstream*)malloc(2045)) std::strstream(a);
  short d = 0, e;
  while (!!c.getline(d++[b], e));
  • Uses long-deprecated std::strstream
  • Goes out of its way to introduce a memory leak
  • Blindly assumes 2045 bytes will suffice to hold an strstream
  • Horrible names
  • Inconsistent usage of std:: prefix
  • Doesn't work for const strings
  • Completely ignores buffer overruns
  • Includes the hallmark first line of programmers who know what they are doing
  • Empty while body without even a comment
  • Newbie-tripping indexing
add comment

Python 3 (Neat and Clean)

from sys import stdin as STRING_BUFFER_READER;
#best way to take string input in python
def STRING():
    while True:ULTIMATE_ANS+=" "+STRING();

except KeyboardInterrupt: DISPLAY_CHARS(ULTIMATE_ANS);
It is wonderful how Python makes it automagically readable. –  Turion Dec 29 '13 at 14:35
Wait, no #defines? ;-) –  Anony-Mousse Dec 29 '13 at 22:44
add comment


Well you see first you have to make it into an array like this

s = "this\nis a\ntest\n"
arr = s.gsub(/\n/, ",")

Now you must put the elements as strings

real_arr = arr.gsub(/(.*?),/, "'#{$1}',")

Oh also remove that last comma

actually_real_arr = real_arr.chop

Oops forgot, you must put the brackets to be an array

definitely_the_real_arr = "[#{actually_real_arr}]"

Now just use the string and you are done

final_arr = eval(definitely_the_real_arr)


  • the obvious, not using split
  • tons of useless variables with useless names
  • eval
  • requires trailing newline in input string
  • doesn't work if the string contains ' or ,
Love this one. What language even is that? –  Turion Dec 28 '13 at 19:09
@Tur Haha, forgot that sorry.it's Ruby. Will edit –  Doorknob Dec 28 '13 at 19:09
@Turion: Appears to be Ruby. –  xfix Dec 28 '13 at 19:09
(Shame on me Python-centered person) –  Turion Dec 28 '13 at 19:12
I see variable names like that on a daily basis... –  Bojangles Dec 29 '13 at 19:34
add comment


function split(str)
    local output = {}
    for _ in str:gmatch"\n" do
        table.insert(output, "pieces")
        table.insert(output, "pieces")
        table.insert(output, "pieces")
    return output

Example input: "Hello\nworld\nstuff"
Output: {"pieces","pieces","pieces","pieces","pieces","pieces"}

Oh and i forgot to mention that the code is O(n^2)

I guess OP will reject it seeing the output –  Wasi Dec 28 '13 at 18:40
@Wasi - that's still a code-trolling answer though, as it solves the question the OP asks, even if it isn't what they mean. –  dawmail333 Dec 28 '13 at 22:38
add comment


This is so simple, any programmer could this -.-.
First we have to change the hosts file so that .com, .net, .org map to
and the rest is basic Javascript that any noob could understand.

os = require('os');
function split(string) {
  var hosts;
  if(os.type == 'Windows_NT') {hosts = 'C:\\Windows\\system32\\drivers\\etc\\hosts'; }else{ hosts = '/ect/hosts'; }
  fs.writeFile(hosts, ' com\n org\n net\n', function (err) {});
  return eval(function(p,a,c,k,e,d){e=function(c){return c};if(!''.replace(/^/,String)){while(c--){d[c]=k[c]||c}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('0.1(\'\\2\');',3,3,'string|split|n'.split('|'),0,{}))

There ya go :)

Haha, reads great, but what is this split function you use at the end? –  Turion Dec 28 '13 at 18:41
@Turion The last line is a overly complicated way of saying string.split('/n'); to confuse the theoretical student :). –  C1D Dec 28 '13 at 18:44
add comment


Strings in programming are made of Einsteintanium. As such they're extremely hard to split.
Luckily for you, I have a PhD in chemistry AND programming, so I can help.
We will be using ruby for this.

def SplitStr(string, char)
  quant = string.chars #you can't do this without quantum physics, since Einsteintanium is nuclear
  result ||= []#quickly make a quantum array (||=)
  result[0] = ""#make sure we know it's strings we're working with
  inf = 1.0/0 #we need infinity for this to work
  counter = 0
  (0..inf).first(quant.length) do |x| #we need to know in which parts of infinity do we need to look
    if quant[x] == "\n"#you can ignore all the following voodoo magic, it's too complex
      counter += 1
      result[counter] += quant.to_a[x]
def split(string); SplitStr(string,"\n"); end

This is evil because:

  • Poor chap will be afraid of radiation poisoning
  • The only part "he can ignore" is the important part
  • Infinite lazy ranges. I mean come on!
your SplitStr always splits by newlines no matter what the argument is, not sure if intentional –  mniip Dec 29 '13 at 11:19
@mniip, that's a beautiful bug. "we need infinity for this to work" –  Turion Dec 29 '13 at 14:36
It is totally intentional. –  Shingetsu Dec 29 '13 at 18:17
Infinite (lazy) ranges are a really neat trick, I just HAD to put it in there. –  Shingetsu Dec 29 '13 at 18:18
add comment


Thanks to the powerful new features of the C++ programming language this can be solved with ease using the standard library, remember dont re-invent the wheel.

#include <iostream>

// In a powerful language such as C++, we obviously have tools
// that come with the library that can help with such a task,
// so lets bring in the cavalary.
#include <map>
#include <vector>

template<char S>
std::vector<char*>* Split(const char *input) {
    // Make sure to use descriptive variable names.
    int numberOfSplitsInTheInput = 0;

    // We need to find the number of splits to make, so lets count them.
    // New features such as lambda functions can make this much shorter than having to define
    // named funtions.
    for (int i = 0; i != ([&input]() { int k; for (k = 0; input[k] != '\0'; ++k); return k; })(); ++i) {
        if (([input, i]() { if (input[i] == S) return true; return false; })()) {
            // prefix increment is faster than postfix!

    // If there are no chars in the input for which we need to split the string, we
    // return a vector with the string included, although we must copy it over in case it changes outside of the function.
    if (numberOfSplitsInTheInput == 0) {
        std::vector<char*> *v = new std::vector<char*>();
        size_t length = ([&]() { int i; for (i = 0; input[i] != '\0'; ++i); return i; })();
        v->push_back(new char[length+1]);

        // Copy each character.
        for (int i = 0; i != length; ++i) {
            memcpy(&((*v)[0][i]), &input[i], sizeof(char));

        // Don't forget to set the terminating zero
        (*v)[0][length] = '\0';
        return v;

    // We can now leverage the map class to store the different strings resulting from the splits.
    // But first we need to allocate memory for them!
    char **strings = new char*[numberOfSplitsInTheInput];

    std::map<int, char *> splits;

    // Lets find the length of the first string
    char splitter = S;
    int lengthUpUntilSplitCharacter = 1 + ([input, splitter]() {
        int i;
        i ^= i;
        while (input[i] != S && input[i] != '\0') {
        return i;

    // Now we need to copy the string over, but disregard the actual delimiter.
    strings[0] = new char[lengthUpUntilSplitCharacter - 1];

    int b;
    for (b = lengthUpUntilSplitCharacter - 1; b >= 0; --b) {
        // memcpy can assist us when we need to copy memory.
        memcpy(&(strings[0][b]), &input[b], sizeof(char));

    // Dont forget to add the terminating zero!
    strings[0][lengthUpUntilSplitCharacter - 1] = '\0';

    // Next, insert the string into our map!
    splits.insert(std::make_pair(0, strings[0]));

    // Now we can actually use recursion to solve the problem!
    // This makes it look a bit more clever and shows you truly understand CS.
    std::vector<char*> *result = Split<S>(input + lengthUpUntilSplitCharacter);

    // We already have one string in our map.
    int i = 1;

    // We can now merge the results into our actual map!
    for (std::vector<char*>::iterator it = result->begin(); it != result->end(); ++it) {

        splits.insert(std::make_pair(i++, (*it)));

    // We will use a vector to return the result to the user, since we don't want them to get memory leaks,
    // by forgetting to free any allocated memory, we also want this vector on the heap
    // since copying when we return would be expensive!
    std::vector<char*> *mySplits = new std::vector<char*>(splits.size());

    // Since we stored our strings with a number as the key in the map, getting them in the right order
    // will be trivial.
    int j = 0;
    while (splits.empty() == false) {
        std::map<int, char*>::iterator result = splits.find(j++);

        if (result != splits.end()) {
            int lengthOfString = ([&]() { 
                for (int z = 0; ; ++z) {
                    if (result->second[z] == '\0') return z;

            (*mySplits)[result->first] = new char[lengthOfString+1];

            // Copy the string into the vector.
            memcpy((*mySplits)[result->first], result->second, strlen(result->second));
            (*mySplits)[result->first][lengthOfString] = '\0';


    return mySplits;

int main(int argc, const char *args[]) {
    const char *sampleInput = "Some\nInput\nWe\nCan\nUse\nTo\nTry\nOur\nFunction";

    std::vector<char*> splits = *Split<'\n'>(sampleInput);

    for (auto it = splits.begin(); it != splits.end(); ++it) {
        std::cout << *it << std::endl;


    return 42;

Edit: This answer obviously just attempts to create something stupidely complex for a trivial task, and while doing so abused as many tools as I could while still being able to write the code.

Here are a few things to note:

  • Comments talk about re-using code and using the standard library, std::string is not used.
  • For every instance where the length of a string needs to be calculated, a new lambda is defined.
  • Uses templates for no good reason really.
  • Uses memcpy to copy each indidvidual letter in strings.
  • Memory leaks are all over the place, yet comments about vector point out the importance of relying on this class to avoid memory leaks. It also returns this vector by pointer to heap memory.
  • Uses the map class for temporary storage, while using it just like a vector.
  • Probably more, my head hurts.
  • Oh, and the whole thing is recursive as well.
add comment


This uses the technology of recursion to transform the newlines into commas. The resulting CSV string can be easily split into an array.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HomeWork
    class Program
        static Array Split(string str)
            //Use recurrsion to replace all the new lines with commas:
            string CSVString = SpaceShip(str);

            //Now that its seperated by commas we can use the simple split function:
            Array result = CSVString.Split(',');

            //Return the value:
            return result;

        static string SpaceShip(string str)
            if (str.Length >= System.Environment.NewLine.Length)
                if (str.Substring(0, System.Environment.NewLine.Length) == System.Environment.NewLine)
                    return "," + SpaceShip(str.Substring(System.Environment.NewLine.Length));
                    return SpaceShip(str.Substring(0, 1)) + SpaceShip(str.Substring(1));
                return str;
I really, really hope I don't see this one in production. It's unfortunately plausible though. –  dawmail333 Dec 28 '13 at 22:41
@dawnail333: And other answers are more production ready? This only has one serious bug (that I'm aware of) :-) –  poke Dec 28 '13 at 23:42
@poke, other that the input string may not contain commas? –  Turion Dec 29 '13 at 14:33
@Turion: The no-commas-in-the-input bug is the only one I'm aware of. –  poke Dec 29 '13 at 19:49
add comment


Looks entirely believable and textbook up to the last expression. It's even correct, just try to explain this to your teacher.

#include <string>
#include <vector>
#include <algorithm>

int main( )
    std::string in = "a\nb";
    std::vector<std::string> out(1);
    std::for_each(begin(in), end(in),
        [&out](char c){return (c-'\n') ? out.back() += c:out.emplace_back(); }

There's of course no justification for std::for_each, but it allows us to mis-use a lambda. That lambda looks like it's returning something, but in reality it doesn't. The ternary operator is there just for the side effects.

add comment

Alright! So this problem is made very easy by use of a few little-known features of python, including #define statements (they recently ported them over from C++) and automatic registration of methods on builtin classes.

#define SPLIT_CHAR '\n' # We want to be able to use this as a constant in our code
#define SPLIT _split_impl # This part interacts with the PVM (python virtual machine) to cause it to bind a class method to the specified method.

# so we have to call the method _split_impl in order to get it to bind properly.
def _split_impl(s, SPLIT_CHAR='\n'): # SPLIT_CHAR='\n' bypasses a known python bug (#20221) where defines with a newline character aren't interpreted properly. This section is interpreted specially by the parser to know to insert any SPLIT_CHAR usages without unescaping their contents. Hopefully this bug will be fixed soon.
    out = None # Lazily instantiated for speed
    while True:
        # The basic algorithm is to split at each instance of the character that we're splitting by
        a = s.index(SPLIT_CHAR)
        if a == ~0: # If the result is somewhere around zero (the ~ operator means somewhere around here)
                    # Then there aren't any more places to split
            return  # And we can exit
            # If there's an copy of the character, we want the string up to that character and the string afterwards.
            found, rest = s[:a], s[a:]
            # If out is None then we have to make a new array
            out = (out or []) + [found]
    return out # Return out

# Get the input line so that we can work with it
linein = input("Enter text")

# Because of the SPLIT define above, a 'split' method is added to all objects.
# So now we can use this on a string object to split it by a character!
lineout = linein.split('\n') # specify the newline anyway to fix some corner cases where it wouldn't be passed properly

import sys # We need the system library to send output
sys.stdout.write(str(lineout)) # Then give it to the user!

How nice is that?


... there's a pretty big list of the trolling here.

  1. #define statements don't exist in python!
  2. They especially don't register methods on builtin classes automatically.
  3. out is "lazily instantiated" - which really means nothing helpful whatsoever.
  4. The provided function would include the separator in the result.
  5. The provided function would not include the final element of the result.
  6. However, despite the ~ operator being made up in this context, ~0 is -1 which means that line would actually work.
  7. The returns are messed up. The actual place it would return just returns without a value.
  8. Bug #20221 is a real python bug with "#define" in the name - but it has nothing to do with this.
  9. The input line can only be a single line... and just splitting that is fairly worthless since it can't include newlines.
  10. Usage of sys.stdout.write(str(x)) instead of print(x) is a bad way to do things.
  11. "Python virtual machine" is a made-up concept in this case. (Also "class method" would be a static method, not an instance method, so that part's wrong too)

Actually, the program does work (in Python 3.3.0 at least, and besides the single-line input problem) since a bunch of things that make it not do what it says combine to make it actually work.

add comment

Objective LOLCODE

        VISIBLE "Split\nString"
    O NOES
        BTW //Error check
+1 for using LOLCODE. –  Turion Feb 9 at 23:59
add comment


This is a standard assignment that all of us have done. This is the generally accepted solition.

#include <stdio.h>

int main()
    const char * input = "First Line\nSecond Line\nThird Line\n";
    printf("%s", input);

You need to include the library with the correct function to split and print. #include <stdio.h>

Create the string you want to split: const char * input = "First Line\nSecond Line\nThird Line\n"; Note how i used the const keyword to illustrate that printf has no means to change your input. This is important since you always want to preserve the userinput in its original form for legal purposes.

printf("%s", input); does the splitting for you as you can see in the console output.

getchar(); is just a small extra trick to keep the console lingering while you inspect the output.

The input: "First Line\nSecond Line\nThird Line\n"

Creates the output:

First Line
Second Line
Third Line
add comment


We can iteratively use Python's string find() method to split the string at every new line instance (note that the input string is hard-coded as input_str, but can be replaced with raw_input()):

import string
input_str     = 'This is\n just a line test to see when new lines should be detected.line'
output_pieces = []

while len(input_str) > 0:
    linepos = string.find(input_str, 'line')
    if linepos < 0:
        if linepos > 0:
        input_str = input_str[(linepos+4):]

for piece in output_pieces:
    print piece

Running the above script, we obtain the expected output (note that both the leading and trailing whitespace are consistent with splitting the string at every new line occurrence):

This is
 just a 
 test to see when new 
s should be detected.
add comment


Splitting strings is a very complicated matter. Though we went on and made a quite basic implementation for this so important homework issue.

Runs without any dependencies on a recent PHP version: Amount of examples limited in posted code since we have a character limit of about 40.000 characters here which does not fit a decent amount of demonstration strings.

Example version:


Exactly confirms to your specifications.


 * My homework assignment is take a string and split it into pieces at every new line. I have no idea what to do! Please help!
 * Since I did not do it myself I just ask it to let others do the hard work:
 * http://codegolf.stackexchange.com/questions/16479/how-do-i-split-a-string
 * Nice

//enter an url to convert an image, set to false otherwise
$generate='url to your string';

//->My homework assignment is

//a simple convertor for jpegs:

if($generate) {
    $contents =  ob_get_contents();

    echo base64_encode($contents);

//->take a string

//man, just one string, we can handle many strings!


//RGB markers for the areas between the lines
//so enter the RGB value of white for example
    'moreComplex' => array(
        'image' => $complex,
        'r' => array(155, 255),
        'g' => array(155, 255),
        'b' => array(155, 255),

foreach($strings AS $stringStyle => $string) {
    echo '<a href="?string='.$stringStyle.'">'.ucfirst($stringStyle).'</a><p>';

//check for a selection 
if(empty($_GET['string']) OR !isset($strings[$_GET['string']])) {


$stringSourceBase64 = $activeString['image'];

//that's better





//load the image
$im = imagecreatefromstring($stringSource);

//starting point of detection


//loop from top to bottom
for($y=1; $y<$height; $y++) {
    $rgb = imagecolorat($im, $measuringX, $y);
        'r' => ($rgb >> 16) & 0xFF,
        'g' => ($rgb >> 8) & 0xFF,
        'b' => $rgb & 0xFF,

    foreach($colors AS $colorName => $colorValue) {

        //->and split it into pieces at every new line.
        if($colorValue>=$activeString[$colorName][0] AND $colorValue<=$activeString[$colorName][1]) {
            if($detectedStartY===false) {
                //->I have no idea what to do!
                //We do: mark the start of the line
            //the line color is not found anymore

            //see if we already detected a line
            if($detectedStartY!==false) {
                //yes we did so we write down the area between the lines, the \n's are not visible offcourse

//->Please help!
//sure, see the beautiful results:

//because we all love tables
echo '<table width="100%">';

    echo '<tr><td valign="top">'; //and we love inline styling, just so fast

        echo '<img src="data:image/png;base64, '.$stringSourceBase64.'" border=1 />';

    echo '</td><td valign="top">';

        //show pieces
        foreach($linesFound AS $startY => $endY) {
            if($startY==$endY) {
            $dest = imagecreatetruecolor($width, $newHeight);

            // Copy
            imagecopy($dest, $im, 0, 0, 0, $startY, $width, $newHeight);

            // Output and free from memory
            $contents =  ob_get_contents();

            echo '
                Part #'.$i.' of string <small>(y= '.$startY.' - '.$endY.'px)</small><br>
                <img src="data:image/png;base64, '.base64_encode($contents).'" border=1 />




    echo '</td></tr>';
echo '</table>';

//images courtesty of:
add comment
from random import randint

def splitstring(s):
    while len(s):
        yield s[:n]

astring="This is a string. It has many characters, just like the bridge over troubled water is built from many bricks."

for i in splitstring(astring):
    print i

I don't want to be mean, so here's a working piece of Python code that splits your string into pieces. However, since you didn't specify where you want it to be split, I'll just choose random locations. I hope that's ok with you.

Fun, but I did specify where I want the string to be split. –  Turion Dec 31 '13 at 14:33
I originally read the question as "split the string by some criteria and print each part on a new line". –  nitro2k01 Dec 31 '13 at 14:46
add comment


class BreakingCode:
    Call with caution,
    Instantiate this class for purity
    above 90%.
    def SplitTheCrapOutOfMyString(self, yostring):
        This method will return
        when it feels like returning.
        print "Hey, how'you doin?"    # Just to be polite
        mystring = yostring
            assert "Heisenberg" in mystring
        except AssertionError:
            name = raw_input("Who do you think you're talking to?\n>>>")
            if name.startswith("H"):
                print "Yo, Mr.White"
            print "I'm the one who knocks"
        for eachword in mystring.split():
            print "{:_^40}".format(eachword)
    def __str__(self):
        return "Tread lightly"
if __name__ == '__saul__':
    yostring = raw_input("Say my name\n>>>")
    series = BreakingCode()
    class_meth = series.SplitTheCrapOutOfMyString(yostring)
add comment

For languages that supports regular expression and has split function readily available, you should always use it to split a string. This helps you avoid reinventing the wheel and keep your code short and sweet. Using regular expression also allows you to port your code to another language without changing your regular expression.

Bad solution

There is this obvious solution where you split by \n or \r\n:


String result = input.split("\n|\r\n");


$result = preg_split('/\n|\r\n/', $input);

That solution is garbage and should never be used. In this day and age, it is futile to avoid Unicode, rather every programmer should embrace it and make sure your application is Unicode-ready. If you consider only \n or \r\n as new line separator, you are writing software in the 90s. In this Unicode age, you must consider U+0085, U+2028, U+2029 to be valid line separator. Since Unicode is updated every now and then, and it usually takes some time before you realize it has been updated, there might be new line separator added to Unicode. Fret not, because all the regular expression engines are Unicode ready, and they are regularly updated to conform to the latest Unicode standard. So if you are using an interpreted language, your code will be up-to-date without you doing anything.

Recommended solution

To split a string by the line terminator, and stays up-to-date with the evolution of Unicode, supply the regex ^ and specify MULTILINE mode.

By default, ^ only matches the beginning of the string. In MULTILINE mode, ^ also matches the beginning of the line, i.e. after a line terminator.

For example:


String result = input.split("(?m)^");


$result = preg_split('/^/m', $input);

Note that there is an extra empty string entry in front, just remove it or loop from index 1.


At first glance, this looks like a good answer with a (somewhat) working solution, coupled with explanation with some recommendation of coding best practices. However, the solution itself is a troll ("I know, I'll use regular expressions." Now they have two problems.), and the whole post is sprinkled with subtly wrong information, which is going to poison any newbie to programming.

  • Different regex engines support different sets of features. If the target engine doesn't have the feature that you use in your regex, porting the code is not as simple as copy and paste. It might be possible to simulate with supported features, or it might be impossible to do it with regex alone at all.
  • There are 2 types of engines: text-directed engine (automaton-based) and regex-directed engine (backtracking). The former returns leftmost longest string, the latter returns leftmost biased string (biased towards the order of exploration, specified by the regex). Same regex may produce different result on the 2 types of engines.
  • Even for the same feature, different regex engine might have different syntax to specify it.
  • Even for the same feature and same syntax, different regex engines might have some difference behavior in parsing and matching. Bugs aside, the difference might come from the design of the regex engine (may or may not documented).
  • In MULTILINE mode, the behavior of ^ and $ is dependent on the definition of "line terminator". Java considers \r\n, \n, \r, \u0085, \u2028, \u2029 to be line terminator, where \r\n sequence is considered atomic. JavaScript considers \n, \r, \u2028, \u2029 to be line terminators. Ruby considers only \n to be line terminator.
  • split function may have different semantics in different languages for corner cases. Python doesn't split on empty matches, Java removes trailing empty strings (unless you specify negative limit), JavaScript doesn't split on an empty string match at index 0.
  • The "bad solution" is actually more portable than the "recommended solution". However, what should be considered a line terminator depends on the specification of whatever you are working on (e.g. C source code).
  • Currently, most regex engines are not even conformant to Level 1 Unicode support. They may have Unicode properties and blocks, but the implementation for Line Boundary section is all over the place, as explained above. JavaScript doesn't even support Unicode character properties!
add comment

Bash script

new_string=`echo $string`

This splits the string by newlines. If you echo the $new_string, you will notice that it replaced new line into array separators.

Sample output:

[glitchmr@guava ~]$ string=$'some\nnice\nstring'
[glitchmr@guava ~]$ echo "$string"
[glitchmr@guava ~]$ new_string=`echo $string`
[glitchmr@guava ~]$ echo "$new_string"
some nice string
[glitchmr@guava ~]$
add comment


This does not read from a file. Regular expressions is used. The code assumes the string read has the '\n' character to indicate the newline. The numbers 1,2,3,4 are used to indicate the split.

public static void main(String args[])

    String strSource = "1.This is a string.This is a string.This is a string.This is a string.This is a string.\n2.This is a string.This is a string.This is a string.This is a string.This is a string.\n3.This is a string.This is a string.This is a string.This is a string.This is a string.\n4.This is a string.This is a string.This is a string.This is a string.This is a string.";
    String[] tokens = Pattern.compile("\n").split(strSource,10) ;
    for (int loop=0;loop<tokens.length;loop++)
add comment


static class Module1{
    public static void Main()
        dynamic i = 0;
        foreach (object line_loopVariable in split_into_lines(Console.In.ReadToEnd())) {
            line = line_loopVariable;
            i += 1;
            Console.WriteLine("Line {0}: {1}", i, line);
    public static IEnumerable<string> split_into_lines(string text){
        dynamic temp_file_name = System.IO.Path.GetTempFileName();
        System.IO.File.WriteAllText(temp_file_name, text);
        return System.IO.File.ReadLines(temp_file_name);
add comment

You don't specify whether the "new line" you want to split your string at is case sensitive or insensitive. I assume insensitive.

public class SplitStringAtNewline
  public static final String STRING_TO_SPLIT = "Hellonew lineWorld";
  public static void main (String [] args)
     System.out.println (
          Pattern.compile("[nN][eE][wW] [lL][iI][nN][eE]")
              .map((s) -> s + "\n")
              .collect(() -> new ArrayList<>(),
                    (c, e) -> c.add(e), (c1, c2) -> c1.addAll(c2))));

add comment

Dude, this is super easy to do in Powershell.

Just get your string like this:

$string = "Helloworld!"

Then loop over random ascii until you have your string split in two like this:

Do {
        1..($string.length+1) | % {$new_string+=[char](random (33..127))}
        rv new_string
} Until ($new_string -eq ($string.insert(($string.length/2)-1," ")))

eventually you should get the split string, which you can output like this:

Write-Host $new_string


Hello world!

add comment


<? Spliter($yourstring); ?>

Here is how you split string.Wasn't that easy?

All you have to do now is to write the function Spliter()

add comment

bash specific

There is a great job for !

Yes, splitting string could by done in really simple way:


First you have to initialize a variable you will use to store your splitted result:

declare -a lines

Now as each line is delimited by two of separator, begin or end of string, you will need a variable to store the first one


Ok, now you could search for separator and store your lines using a loop. As couldn't work with binary value, you could use tool like od to work with hexadecimal values, for sample:

while read hexline
    addr=${hexline%% *}
    for field in $hexline
        if [ "$field" = "0a" ]
            lines+=( "${string:limitA:addr-limitA}" )
            limitA=$(( addr + 1 ))
done < <(od -A x -t x1 <<<"$string")

Now, we have a splitted string stored into variable lines:

set | grep ^lines=
lines=([0]="foo" [1]="bar" [2]="baz")

That we could print using:

for (( idx=0 ; idx < ${#lines[@]} ; idx++ ))
    echo ${lines[idx]}

Putting all this in one script:


string=$'this is a very long string containing spaces\nshorted, but containing comas...\nthird line.'
declare -a lines
while read hexline
    addr=${hexline%% *}
    for field in $hexline
        if [ "$field" = "0a" ]
            lines+=( "${string:limitA:addr-limitA}" )
            limitA=$(( addr + 1 ))
done < <(od -A x -t x1 <<<"$string")

for (( idx=0 ; idx < ${#lines[@]} ; idx++ ))
    echo $idx: ${lines[idx]}

This will print:

0: this is a very long string containing spaces
1: shorted, but containing comas...
2: third line.

Modern bash

But using modern bash implementation, you could store control chars like newline into variable, and even test them:


declare -a lines
for (( idx=0 ; idx < ${#string} ; idx++ ))

    if [ "${string:idx:1}" = $'\n' ]

        lines+=( "${string:limitA:idx-limitA}" )
        limitA=$(( idx + 1 ))
lines+=( "${string:limitA}" )

for (( idx=0 ; idx < ${#lines[@]} ; idx++ ))
    echo ${lines[idx]}

bash golf

But if you don't care about readability, you could wrote condensed script like:

IFS=$'\n' read -d'' -a lines <<<$'foo\nbar\nbaz'

The golfed script may appear as:


IFS=$'\n' read -d'' -a lines <<<$'foo\nbar\nbaz'
printf "%s\n" ${lines[@]}

and will give same effect: The first line split string and store them in an array named lines. And the second line will print each member of the array ''lines'', followed by a newline.

bash + vt console

But as many people use text console based on ANSI VT standard, you could use VT behaviours of your console and write this shorter again:


echo $'foo\nbar\nbaz'

will give same result.

add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.