How do I split a string??? Help plz? (code trolling)



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.


Posted 2013-12-28T18:15:46.513

Reputation: 445

Question was closed 2014-05-12T12:22:43.130

1Is this a [tag:popularity-contest] or [tag:code-golf]? – osvein – 2013-12-30T22:55:53.457

@user1981338, neither, read the wiki of the code-trolling tag. – Turion – 2013-12-31T14:32:47.150


Here's a valuable resource I found regarding string splitting... I hope you find it useful!

– WallyWest – 2014-01-08T07:49:18.837

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 – 2014-05-12T12:22:19.003

@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 – 2014-05-12T12:54:39.377

Thanks for your input, @Turion! As I said, this post is... different - it does have many votes, but the community wants (in the poll and as expressed in chat) it to be deleted, as it is very underspecified. If you'd like, you can join us in chat now to discuss this.

– Doorknob – 2014-05-12T12:58:07.530

After further consideration, according to input in chat and on meta, this post is being locked instead. – Doorknob – 2014-05-13T12:16:11.753




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

HostileFork says dont trust SE

Posted 2013-12-28T18:15:46.513

Reputation: 2 292

11Return 1 for success. Glorious. – Turion – 2013-12-30T18:29:23.840

3Awsome to the max :) – Johannes – 2014-01-01T22:34:06.177

3Damn this one is pure evil. – Thom Wiggers – 2014-01-04T12:05:37.537


  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.


Posted 2013-12-28T18:15:46.513

Reputation: 719

I tried not working... – rakeshNS – 2014-01-01T07:17:30.297

30I got "Exception: Unsafe operation. Do not run with scissors" – Paul – 2014-01-05T10:58:14.207

1My rock crushed the scissors! D'oh! – bobbel – 2014-04-09T12:03:33.693

My scissors accidentally cut the instructions...Seg fault? – David Wilkins – 2014-04-11T14:03:30.973



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.


Posted 2013-12-28T18:15:46.513

Reputation: 8 901

Try to do it in one line, for extra credits!!!1! – Has QUIT--Anony-Mousse – 2013-12-29T22:41:08.520

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! – HostileFork says dont trust SE – 2014-01-16T04:49:07.610



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)


Posted 2013-12-28T18:15:46.513

Reputation: 545

2Wow!!! That's soooo evil....I want to vote twice!!!!!!!! – Fabricio Araujo – 2014-01-08T17:57:31.843


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 =
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.

Gilles 'SO- stop being evil'

Posted 2013-12-28T18:15:46.513

Reputation: 2 531


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


Posted 2013-12-28T18:15:46.513

Reputation: 5 283

9Every VB introduction should be firmly founded in a solid understanding of monads! – Christopher Creutzig – 2013-12-28T20:22:14.107



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 ,


Posted 2013-12-28T18:15:46.513

Reputation: 68 138

Love this one. What language even is that? – Turion – 2013-12-28T19:09:09.277

@Tur Haha, forgot that's Ruby. Will edit – Doorknob – 2013-12-28T19:09:34.030

@Turion: Appears to be Ruby. – Konrad Borowski – 2013-12-28T19:09:39.860

(Shame on me Python-centered person) – Turion – 2013-12-28T19:12:00.600

3I see variable names like that on a daily basis... – Bojangles – 2013-12-29T19:34:03.827



                                                                                                                                                                                                                      #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

Christopher Creutzig

Posted 2013-12-28T18:15:46.513

Reputation: 383


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


Posted 2013-12-28T18:15:46.513

Reputation: 1 682

2It is wonderful how Python makes it automagically readable. – Turion – 2013-12-29T14:35:03.833

Wait, no #defines? ;-) – Has QUIT--Anony-Mousse – 2013-12-29T22:44:23.737



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)


Posted 2013-12-28T18:15:46.513

Reputation: 9 396

2I guess OP will reject it seeing the output – Wasi – 2013-12-28T18:40:59.630

1@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. – Liam Dawson – 2013-12-28T22:38:54.350



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


Posted 2013-12-28T18:15:46.513

Reputation: 590

Haha, reads great, but what is this split function you use at the end? – Turion – 2013-12-28T18:41:52.167

@Turion The last line is a overly complicated way of saying string.split('/n'); to confuse the theoretical student :). – C1D – 2013-12-28T18:44:38.427



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!


Posted 2013-12-28T18:15:46.513


1your SplitStr always splits by newlines no matter what the argument is, not sure if intentional – mniip – 2013-12-29T11:19:49.317

@mniip, that's a beautiful bug. "we need infinity for this to work" – Turion – 2013-12-29T14:36:28.777

It is totally intentional. – None – 2013-12-29T18:17:46.473

Infinite (lazy) ranges are a really neat trick, I just HAD to put it in there. – None – 2013-12-29T18:18:10.210



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.


Posted 2013-12-28T18:15:46.513

Reputation: 41



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;


Posted 2013-12-28T18:15:46.513

Reputation: 221

I really, really hope I don't see this one in production. It's unfortunately plausible though. – Liam Dawson – 2013-12-28T22:41:38.657

@dawnail333: And other answers are more production ready? This only has one serious bug (that I'm aware of) :-) – poke – 2013-12-28T23:42:17.780

@poke, other that the input string may not contain commas? – Turion – 2013-12-29T14:33:55.780

@Turion: The no-commas-in-the-input bug is the only one I'm aware of. – poke – 2013-12-29T19:49:58.607



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.


Posted 2013-12-28T18:15:46.513

Reputation: 171


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.

Cel Skeggs

Posted 2013-12-28T18:15:46.513

Reputation: 901


Objective LOLCODE

        VISIBLE "Split\nString"
    O NOES
        BTW //Error check


Posted 2013-12-28T18:15:46.513

Reputation: 421



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


Posted 2013-12-28T18:15:46.513

Reputation: 199



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.


Posted 2013-12-28T18:15:46.513

Reputation: 620



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:
 * 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:

Luc Franken

Posted 2013-12-28T18:15:46.513

Reputation: 121


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.


Posted 2013-12-28T18:15:46.513

Reputation: 1 283

Fun, but I did specify where I want the string to be split. – Turion – 2013-12-31T14:33:26.043

I originally read the question as "split the string by some criteria and print each part on a new line". – nitro2k01 – 2013-12-31T14:46:54.273



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)

Renae Lider

Posted 2013-12-28T18:15:46.513

Reputation: 1 474


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!


Posted 2013-12-28T18:15:46.513

Reputation: 5 683


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 ~]$

Konrad Borowski

Posted 2013-12-28T18:15:46.513

Reputation: 11 185



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


Posted 2013-12-28T18:15:46.513

Reputation: 11



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


Posted 2013-12-28T18:15:46.513

Reputation: 11


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



Posted 2013-12-28T18:15:46.513

Reputation: 211


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!

Vasili Syrakis

Posted 2013-12-28T18:15:46.513

Reputation: 181


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.

F. Hauri

Posted 2013-12-28T18:15:46.513

Reputation: 2 654



<? Spliter($yourstring); ?>

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

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


Posted 2013-12-28T18:15:46.513

Reputation: 2 019



splitStr str = split prefixes  
    where prefixes = map (\x -> splitAt x str) [1..(length str)]

split [] = []
split (a:b)
    | head (reverse x) == '\n'    =   [x] ++ splitStr y
    | otherwise = split b
    where x = fst a
          y = snd a

main = print (splitStr "abc\ndef\nghi")


Posted 2013-12-28T18:15:46.513

Reputation: 695

I may be missing something, but how is this code trolling? Apart from being slightly convoluted with the head (reverse x), of course. – Christopher Creutzig – 2013-12-28T20:20:34.833

It's trolling because there is already a function to do this quite simply: lines. I came up with a terrible way to implement. The terribleness of my solution should be obvious. Let the downvotes commence. – danmcardle – 2013-12-29T03:27:09.920

It might help to add a few comments below your code. – Christopher Creutzig – 2013-12-29T09:34:31.157

4That's the trolling part of Haskell. You never know if the solution is considered elegant or trolling. Maybe lines is even implemented like this! – Has QUIT--Anony-Mousse – 2013-12-29T22:47:39.673



Replace the "any text to split \n next line\n another line" (without quotes) with the text you want to split:

#!/usr/bin/perl -w

my @array = split("\n", "any text to split \n next line\n another line");
print "@array";


But you can do it much simpler. In C, you can include on a header file containing the solution.

#include "howtosplitstrings.h"


Posted 2013-12-28T18:15:46.513

Reputation: 51



public static String[] splitOnNewlines(String str)
    ByteArrayInputStream bais = new ByteArrayInputStream(str.getBytes());
    BufferedReader br = new BufferedReader(new InputStreamReader(bais));
    List<String> l = new ArrayList<String>();
    String m;
    while ((m = br.readLine()) != null) l.add(m);
    return m.toArray(new String[l.size()]);

This isn't really horrific, but still totally not done.

Martijn Courteaux

Posted 2013-12-28T18:15:46.513

Reputation: 759



In Java you can achieve that by just 2 lines of code

sentence="What ever your sentence is, it comes here";
String [] splitSentence=sentence.split("\n");
        for(String s:splitSentence)
        System.out.println(s);// print it or do what ever you want to do with that. Now s contains you'r splited String.


Posted 2013-12-28T18:15:46.513

Reputation: 101

4Are you sure this is code trolling? This looks like an actual solution. – Joe Z. – 2013-12-29T16:24:11.520

I prefer System.out.println(sentence); for the purpose of complexity. – Has QUIT--Anony-Mousse – 2013-12-29T22:45:48.023



As you may know, Python is slow sometimes. But if you know some undocumented internal features, heavy operations like searching and splitting could be optimized. Way faster than regular expressions!

# can be replaced with raw_input()
input_string = 'here is a string i wanna split\njust a string\nim gonna split it now'

magic_key = 495807392116L #  Popov-Shlaustas key for 64-bit hardware

def optimized_split(key):
    Doing split by taking advantage of 64-bit memory segmentation
    while key:
        yield chr(key % 256)
        key >>= 8

def find_newlines(num):
    Optimized way to scan string for newlines, using bitwise operations
    while num/10:
        if num / 100 and not num / 200:
            num <<=7
        elif not (num ^ 15724) - 236:
            num /= 60
        elif num < 100000 and num / 200:
            num += 123456
        elif num ^ 15000 ^ 1688:
            num >>= 1
    return num / 12371

print getattr(input_string, ''.join(reversed(list(optimized_split(magic_key)))))(chr(find_newlines(123)))

Ivan Anishchuk

Posted 2013-12-28T18:15:46.513

Reputation: 111


Golf-Basic 84


The right tool for the job!

Outputs the input, because GB84 doesn't support newlines ^_^


Posted 2013-12-28T18:15:46.513

Reputation: 12 038



This is a very hard problem (NP Complete in fact). However there exists a recursive solution :

public String[] split(String str) {
  String[] answer = null;
  try {
    answer = split(str);
  } finally {
    if (answer == null) {
      return new String[1];
    } else {
      for (int i = 0; i < answer.length; i++) {
        if (answer[i] != null) {
          str = str.substring(answer[i].length()
              + (i < answer.length - 1 ? 1 : 0), str.length());
      if (str.isEmpty()) {
        return answer;
      if (answer[answer.length - 1] == null) {
        answer[answer.length - 1] = "";
      char c = str.charAt(0);
      if (c == '\n') {
        return Arrays.copyOf(answer, answer.length + 1);
      } else {
        answer[answer.length - 1] += c;
        return answer;


Posted 2013-12-28T18:15:46.513

Reputation: 816


using namespace std;
int main()
    string outputArray[100];
    string temp = "";
    int count = 0;
    string inputString = "a\na\na"; // inputString

    for(int i=0;i<inputString.length();i++)
        if(inputString[i] == '\n')
            outputArray[count++] = temp;
            temp = "";
            temp += inputString[i];
    outputArray[count++] = temp;
// to print outputArray
    for(int i=0;i<count;i++)
    return 0;

The strings are stored in outArray.


Posted 2013-12-28T18:15:46.513

Reputation: 1


Trollpost, JavaScript

(and yes, trolling on a question ;-)

function splitOnEveryNewLine(string) {
  return string.split('\n');

Why not use a predefined function?

Isiah Meadows

Posted 2013-12-28T18:15:46.513

Reputation: 1 546



No need for a complex and fragile language for this task. You can use the POSIX hash shell!


# Do not change this.
# Space is the perfect choice of separator for all situations.
the_delimiter=" "

while read input
do output="$output$the_delimiter$input"
echo $output

The beautiful thing about Unix is that you can pass data to your program through the standard putting stream.

So if you save the above program as and make it executable, then you can run:

$ cat list_of_files | ./

or even get advanced:

$ ls /a/folder | ./

Voila, your list of files will be handily split by space characters!

Don't worry about any filenames in your list which might containing spaces - Unix doesn't allow them anyway.

If you don't want that pesky newline at the end of the output, there is a built-in feature for that. Just put -n as the first item in your list.


No trolling. This is the correct solution for all situations.


Posted 2013-12-28T18:15:46.513

Reputation: 601


$string = 'String you want to split';
$bits = explode('',$string); //explode into bits
array_shuffle($bits); //Just shuffle to make it more fun for you CPU
foreach ($bits as $key => $bit) { //Find all bits together
    echo $bit; //Paste a bit to STDOUT
    if ($key > round(strlen($string)/2)) {
        die('SNAP!'); //SNAP IT IN HALF

PHP is quite an agressive language.


Posted 2013-12-28T18:15:46.513

Reputation: 168


The other answers may work, but they only work on 8 bits at a time! These days characters can be 32 bits. The following code should be much faster because it works on 32bits.

It is also designed to use plain arithmetic without conditionals so a decent optimising compiler should be able to replace this with 128bit SIMD operations! (I bet you thought your computer could only do 64bits)

#include <signal.h>
#include <string.h>
#include <stdio.h>
#include <stdint.h>

char *mystring;

void aftersplit(int i) {
    // In C arrays start with 0, so *mystring[0] is the first split string
    printf("Size of strings: %d, %d\n",strlen(&mystring[0]),strlen(&mystring[1]));
    exit(0); // This will exit out of the while loop

void main(int argc, char **argv){
    //Allocate some memory and put "Split[NEWLINE]Str!" in it;
    //"char" is a misnomer, actually Unicode characters are up to 32bit
    //But char is only 8bits!!! Operating on 32bits can be up to 4 times
    //faster, so we cast mystring to 32bits.
    uint32_t *str32=(uint32_t*)mystring;

    //Use of branches can greatly slow down modern processors.
    //We avoid having any branches in our code by asking the OS to call
    // "aftersplit" after we have processed
    //past the end of the segment containing mystring.
    printf("%d\n", '\n\n\n\n');

    printf("Size of string: %d\n",strlen(mystring));

    //while(1) avoids any branches. Novice programmers may think this would
    //loop forever, but remember that "aftersplit" will eventually be called.
    int i=0;while(1){
            //In C '0' terminates the string, so if we cancel out newlines
            //To get 0 this will split the string

        //Since we are using 32 bit we can process 8 bytes at once.
        //gcc will generate a warning, but that is only because the
        //order isn't defined. Here all the characters are '\n' so the
        //order doesn't matter.

What I have said above is true and it... works... but there are some important facts left out:

  • The "Segment containing the string" contains all the mutable program data, so we trash memory. Getting a SIGSEGV signal isn't a way of detecting the end of a string.
  • The resulting strings are unrecognisable since we have subtracted '\n' from each character.
  • the resulting mystring is not an array of strings. The only reason mystring[1] has the the length of the second string is because it is one less than the length of the first string. The second string is actually (mystring+strlen(mystring)+1).


Posted 2013-12-28T18:15:46.513

Reputation: 676



split = []
line = ''
count = 0
for char in string:
    count = count + 1
    if char != '\n':
        line = line + char
        if count == len(string):
        line = ''

Make sure that you append after the string length has been met otherwise you'll be missing part of the assignment.

It should work like this:

the quick brown fox
jumped over the lazy dog
and ate the programmer

['the quick brown fox', 'jumped over the lazy dog', 'and ate the programmer']



Posted 2013-12-28T18:15:46.513

Reputation: 117



from sys import stdout as o
i=raw_input("Give me string plz? ")
for x in i+"\n": o.write(x) if x!="\n" else o.write("\n")

Hannes Karppila

Posted 2013-12-28T18:15:46.513

Reputation: 3 090

please read the description of the tag. – Mhmd – 2014-04-21T08:57:58.253