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 code-trolling question. Please do not take the question and/or answers seriously. More information here.
Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It only takes a minute to sign up.
Sign up to join this communityMy 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 code-trolling question. Please do not take the question and/or answers seriously. More information here.
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")
head (reverse x)
, of course.
\$\endgroup\$
Dec 28, 2013 at 20:20
lines
. I came up with a terrible way to implement. The terribleness of my solution should be obvious. Let the downvotes commence.
\$\endgroup\$
Dec 29, 2013 at 3:27
lines
is even implemented like this!
\$\endgroup\$
Dec 29, 2013 at 22:47
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"
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.
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.
System.out.println(sentence);
for the purpose of complexity.
\$\endgroup\$
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)))
i`Od`O
The right tool for the job!
Outputs the input, because GB84 doesn't support newlines ^_^
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;
}
}
}
}
#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.
(and yes, trolling on a code-trolling question ;-)
function splitOnEveryNewLine(string) {
return string.split('\n');
}
Why not use a predefined function?
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.
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:
SIGSEGV
signal isn't a way of detecting the end of a string.'\n'
from each character.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)
.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:\>
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")