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

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!

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

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

• I may be missing something, but how is this code trolling? Apart from being slightly convoluted with the head (reverse x), of course. Dec 28, 2013 at 20:20
• 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. Dec 29, 2013 at 3:27
• It might help to add a few comments below your code. Dec 29, 2013 at 9:34
• 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! Dec 29, 2013 at 22:47

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"


Java

public static String[] splitOnNewlines(String str)
{
ByteArrayInputStream bais = new ByteArrayInputStream(str.getBytes());
List<String> l = new ArrayList<String>();
String m;
return m.toArray(new String[l.size()]);
}


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

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.

• Are you sure this is code trolling? This looks like an actual solution. Dec 29, 2013 at 16:24
• I prefer System.out.println(sentence); for the purpose of complexity. Dec 29, 2013 at 22:45

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


Golf-Basic 84

iOdO


The right tool for the job!

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

Java

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

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

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

Trollpost, JavaScript

(and yes, trolling on a question ;-)

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


Why not use a predefined function?

#!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=""
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.

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

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

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


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

• please read the description of the tag. Apr 21, 2014 at 8:57