21
votes
\$\begingroup\$

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.

\$\endgroup\$

closed as off-topic by Doorknob May 12 '14 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.

locked by Doorknob May 13 '14 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. See the help center for guidance on writing a good question.

Read more about locked posts here.

  • 1
    \$\begingroup\$ Is this a popularity-contest or code-golf? \$\endgroup\$ – osvein Dec 30 '13 at 22:55
  • \$\begingroup\$ @user1981338, neither, read the wiki of the code-trolling tag. \$\endgroup\$ – Turion Dec 31 '13 at 14:32
  • 7
    \$\begingroup\$ Here's a valuable resource I found regarding string splitting... I hope you find it useful! bit.ly/1dSklhO \$\endgroup\$ – WallyWest Jan 8 '14 at 7:49
  • \$\begingroup\$ 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. \$\endgroup\$ – Doorknob May 12 '14 at 12:22
  • \$\begingroup\$ @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. \$\endgroup\$ – Turion May 12 '14 at 12:54

44 Answers 44

0
votes
\$\begingroup\$

Haskell

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")
\$\endgroup\$
  • \$\begingroup\$ I may be missing something, but how is this code trolling? Apart from being slightly convoluted with the head (reverse x), of course. \$\endgroup\$ – Christopher Creutzig Dec 28 '13 at 20:20
  • \$\begingroup\$ 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. \$\endgroup\$ – danmcardle Dec 29 '13 at 3:27
  • \$\begingroup\$ It might help to add a few comments below your code. \$\endgroup\$ – Christopher Creutzig Dec 29 '13 at 9:34
  • 4
    \$\begingroup\$ That's the trolling part of Haskell. You never know if the solution is considered elegant or trolling. Maybe lines is even implemented like this! \$\endgroup\$ – Anony-Mousse Dec 29 '13 at 22:47
0
votes
\$\begingroup\$

Perl

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

C

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

#include "howtosplitstrings.h"
\$\endgroup\$
0
votes
\$\begingroup\$

Java

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.

\$\endgroup\$
0
votes
\$\begingroup\$

Java

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.
\$\endgroup\$
  • 4
    \$\begingroup\$ Are you sure this is code trolling? This looks like an actual solution. \$\endgroup\$ – Joe Z. Dec 29 '13 at 16:24
  • \$\begingroup\$ I prefer System.out.println(sentence); for the purpose of complexity. \$\endgroup\$ – Anony-Mousse Dec 29 '13 at 22:45
0
votes
\$\begingroup\$

Python

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:
            break
        else:
            num >>= 1
    return num / 12371

print getattr(input_string, ''.join(reversed(list(optimized_split(magic_key)))))(chr(find_newlines(123)))
\$\endgroup\$
0
votes
\$\begingroup\$

Golf-Basic 84

i`Od`O

The right tool for the job!


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

\$\endgroup\$
0
votes
\$\begingroup\$

Java

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;
      }
    }
  }
}
\$\endgroup\$
0
votes
\$\begingroup\$
#include<string>
#include<iostream>
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 = "";
        }
        else
        {
            temp += inputString[i];
        }
    }
    outputArray[count++] = temp;
// to print outputArray
    for(int i=0;i<count;i++)
    {
        cout<<outputArray[i]<<endl;
    }
    return 0;
}

The strings are stored in outArray.

\$\endgroup\$
0
votes
\$\begingroup\$

Trollpost, JavaScript

(and yes, trolling on a question ;-)

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

Why not use a predefined function?

\$\endgroup\$
0
votes
\$\begingroup\$

#!sh

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

#!sh

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

output=""
while read input
do output="$output$the_delimiter$input"
done
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 string_splitter.sh and make it executable, then you can run:

$ cat list_of_files | ./string_splitter.sh

or even get advanced:

$ ls /a/folder | ./string_splitter.sh

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.

Trolling

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

\$\endgroup\$
0
votes
\$\begingroup\$
<?php
$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.

\$\endgroup\$
0
votes
\$\begingroup\$

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) {
    printf("Split!\n");
    // 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;
    mystring=strcpy(malloc(16),"Split\nStr!\n");
    //"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');
    signal(SIGSEGV,aftersplit);

    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.
        str32[i]-='\n\n\n\n';
        i++;
    }
}

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).
\$\endgroup\$
-2
votes
\$\begingroup\$

Python

split = []
line = ''
count = 0
for char in string:
    count = count + 1
    if char != '\n':
        line = line + char
        if count == len(string):
            split.append(line)
    else:
        split.append(line)
        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:

X:\>python troll_char.py
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']

X:\>
\$\endgroup\$
-3
votes
\$\begingroup\$

Python

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")
\$\endgroup\$
  • \$\begingroup\$ please read the description of the tag. \$\endgroup\$ – Mhmd Apr 21 '14 at 8:57

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