Take the 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.

share|improve this question
add comment

25 Answers

Python

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.

share|improve this answer
 
Try to do it in one line, for extra credits!!!1! –  Anony-Mousse 12 hours ago
add comment

C

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 }

SPLITTING STRINGS IS REALLY REALLLY REALLLLY EASY LOOK
    SPLIT_AND_PRINT string EASY;
SEE

Call it like this:

split("a\nb");

Working example:

http://codepad.org/GBHdz2MR

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)
share|improve this answer
add comment

Ruby

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

Evilness:

  • 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 quotes or commas
share|improve this answer
 
Love this one. What language even is that? –  Turion yesterday
 
@Tur Haha, forgot that sorry.it's Ruby. Will edit –  Doorknob of Snow yesterday
 
@Turion: Appears to be Ruby. –  GlitchMr yesterday
 
(Shame on me Python-centered person) –  Turion yesterday
 
I see variable names like that on a daily basis... –  Bojangles 15 hours ago
add comment

Visual Basic

The IO monad has a function to do that!

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)
        Next
    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)
        Return IO.File.ReadLines(temp_file_name)
    End Function
End Module
share|improve this answer
2  
Every VB introduction should be firmly founded in a solid understanding of monads! –  Christopher Creutzig yesterday
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 your string is still not split, repeat the steps until it's split. If you have repeated the steps a couple of times and the string is till not split, try grab a sharper scissor.

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

share|improve this answer
 
+1 Really good answer. –  Victor 2 hours ago
add comment

Lua

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

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)

share|improve this answer
2  
I guess OP will reject it seeing the output –  Wasi yesterday
 
@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 yesterday
add comment

Node.JS

This is so simple, any programmer could this -.-.
First we have to change the hosts file so that .com, .net, .org map to 127.0.0.1.
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, '127.0.0.1 com\n 127.0.0.1 org\n 127.0.0.1 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 :)

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

Python


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:
        output_pieces.append(input_str)
        break
    else:
        if linepos > 0:
            output_pieces.append(input_str[0:linepos])
        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.
share|improve this answer
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"
some
nice
string
[glitchmr@guava ~]$ new_string=`echo $string`
[glitchmr@guava ~]$ echo "$new_string"
some nice string
[glitchmr@guava ~]$
share|improve this answer
add comment

C#

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));
                }
                else
                {
                    return SpaceShip(str.Substring(0, 1)) + SpaceShip(str.Substring(1));
                }
            }
            else
            {
                return str;
            }
        }
    }
}
share|improve this answer
 
I really, really hope I don't see this one in production. It's unfortunately plausible though. –  dawmail333 yesterday
 
@dawnail333: And other answers are more production ready? This only has one serious bug (that I'm aware of) :-) –  poke yesterday
 
@poke, other that the input string may not contain commas? –  Turion 20 hours ago
 
@Turion: The no-commas-in-the-input bug is the only one I'm aware of. –  poke 15 hours ago
add comment

ANSI C

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);
    getchar();
}

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
share|improve this answer
add comment

C++

                                                                                                                                                                                                                      #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
share|improve this answer
add comment

Ruby

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
    else
      result[counter] += quant.to_a[x]
  end
  end
end
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!
share|improve this answer
1  
your SplitStr always splits by newlines no matter what the argument is, not sure if intentional –  mniip 23 hours ago
 
@mniip, that's a beautiful bug. "we need infinity for this to work" –  Turion 20 hours ago
 
It is totally intentional. –  Shingetsu 16 hours ago
 
Infinite (lazy) ranges are a really neat trick, I just HAD to put it in there. –  Shingetsu 16 hours ago
add comment

Python 3 (Neat and Clean)

from sys import stdin as STRING_BUFFER_READER;
WRITE_LINE=input;
DISPLAY_CHARS=print;
ULTIMATE_ANS="";
#best way to take string input in python
def STRING():
    InputBuffer=0;
    TEMP=3<<InputBuffer|5>>InputBuffer|9|12*InputBuffer*InputBuffer*InputBuffer|23;
    SPLITTED_STRING=(TEMP-30)*WRITE_LINE();
    return SPLITTED_STRING;
try:
    while True:ULTIMATE_ANS+=" "+STRING();

except KeyboardInterrupt: DISPLAY_CHARS(ULTIMATE_ANS);
share|improve this answer
 
It is wonderful how Python makes it automagically readable. –  Turion 20 hours ago
 
Wait, no #defines? ;-) –  Anony-Mousse 12 hours ago
add comment

Java

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++)
        System.out.println(tokens[loop]);
}
share|improve this answer
add comment

C#

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);
    }
}
share|improve this answer
add comment

PHP / GD

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:

http://codepad.viper-7.com/YnGvCn

Exactly confirms to your specifications.

<?PHP

/**
 * 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';
$generate=false;

//->My homework assignment is
$boring=true;

//a simple convertor for jpegs:

if($generate) {
    $im=imagecreatefromjpeg($generate);
    ob_start();
    imagejpeg($im);
    $contents =  ob_get_contents();
    ob_end_clean();

    echo base64_encode($contents);
    exit;
}



//->take a string

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

$complex=<<<'EOT'
/9j/4AAQSkZJRgABAQAAAQABAAD//gA+Q1JFQVRPUjogZ2QtanBlZyB2MS4wICh1c2luZyBJSkcgSlBFRyB2ODApLCBkZWZhdWx0IHF1YWxpdHkK/9sAQwAIBgYHBgUIBwcHCQkICgwUDQwLCwwZEhMPFB0aHx4dGhwcICQuJyAiLCMcHCg3KSwwMTQ0NB8nOT04MjwuMzQy/9sAQwEJCQkMCwwYDQ0YMiEcITIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIy/8AAEQgBQADuAwEiAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+v/EAB8BAAMBAQEBAQEBAQEAAAAAAAABAgMEBQYHCAkKC//EALURAAIBAgQEAwQHBQQEAAECdwABAgMRBAUhMQYSQVEHYXETIjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEXGBkaJicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uLj5OXm5+jp6vLz9PX29/j5+v/aAAwDAQACEQMRAD8A9/NJSmkoAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigBTSUppKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAU0lKaSgAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAFNJSmkoAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigBTSUppKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAU0lFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRmigAooooAKDSmmk0AGaTcK4nUviHbp4gm0HRdOudY1GD/j5MTLHBb/AO/K3H5A9COoxVbVfFfiqwVJbXQtIvAF/eQQ6jIHz7F4lU/qfaiwHo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vcV9GeDNAi0Dw/ZaemD5MYDkE/Mx5Zh9WJOO2azny9BnSQJhQKtqKiRalFSAtFFFABRRRQAUUUUAFFFFABRRRQAGilNJQAUZoooAM0ZooxQAZooxRQAUUUUAFFFFAFeZMqa4rX4W0/WNN1FVGxZvInOOkcg28YHZxGeoGAe+K7xhmszUtNhv7d4ZokkjYYKuoIP4GkBQidehPTtU/mJ26+1cqPAEKO2y+1gKx6f2rc8f8Aj9WbfwQsXH2vUmHpJqVw/wDNzTAsagv9qarp9guGjST7XOMZBVQRGCD0y5DAjvH2rqYItigdhVLS9Hg0yLZCgXcckjufUnvWsq0gFUU6iimAZooxRQAUZooxQAUUUUAGaKMUUAFFFFACmkoooAKKKM0AFFGaM0AFFGaKACiiigAooozQAUhGaXNGaAGbBRsFPooATaKWjNGaACijNFABRRRmgAoozRmgAoozRmgAoozRQAUUUUAFFKaSgAoxRRQAYoxRRQAUUUUAFFFFABRiiigAxRiiigAooooAKMUUUAGKKKKACjFFFABijFFFABijFFFABiiiigAooooAU0lBooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigBTSc0GjNABzRzRRQAc0c0UUAHNHNFGaADmjmjNFABzRzRRQAc0c0ZooAOaOaM0ZoAOaOaKKADmjmiigA5o5oozQAc0c0ZozQAc0c0ZooAOaOaKKADmjmjNGaAFpMUtFACYoxS0UAJijFLRQAmKMUtFACYoxS0UAJijFLRQAmKMUtFACYoxS0UAJijFLRQAmKMUtFACUUtFACYoxS0UAJijFLRQAmKMUtFACYoxS0UAf/9k=
EOT;


//RGB markers for the areas between the lines
//so enter the RGB value of white for example
$strings=array(
    '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']])) {
    exit;
}

$activeString=$strings[$_GET['string']];

$stringSourceBase64 = $activeString['image'];

//that's better

$stringSource=base64_decode($stringSourceBase64);

$sizes=getimagesizefromstring($stringSource);

$width=$sizes[0];
$height=$sizes[1];

$measuringX=round($width*.5);

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

//starting point of detection
$detectedStartY=false;
$linesFound=array();

$lastEndedY=false;

//loop from top to bottom
for($y=1; $y<$height; $y++) {
    $rgb = imagecolorat($im, $measuringX, $y);
    $colors=array(
        '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
                $detectedStartY=$y;
            }
        }else{
            //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
                $linesFound[$detectedStartY]=$y;
                $detectedStartY=false;
            }
        }
    }
}

//->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
        $i=0;
        foreach($linesFound AS $startY => $endY) {
            if($startY==$endY) {
                continue;
            }
            $newHeight=$endY-$startY;
            $dest = imagecreatetruecolor($width, $newHeight);

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

            // Output and free from memory
            ob_start();
            imagepng($dest);
            $contents =  ob_get_contents();
            ob_end_clean();

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

            imagedestroy($dest);

            $i++;
        }

        imagedestroy($im);

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

//images courtesty of:
//http://indulgy.net/cC/V8/MF/0002501105.jpg
//http://2.bp.blogspot.com/_JGIxXn5d7dc/TBbM2Zu8qRI/AAAAAAAAABE/8WlYvhPusO8/s320/thong4.jpg
//http://cdn.iofferphoto.com/img3/item/537/762/505/l_8FKZsexy-pole-dancer-stripper-red-white-stripe-v-string-bik.jpg
//
//http://stackoverflow.com/questions/2329364/how-to-embed-images-in-a-single-html-php-file
share|improve this answer
add comment

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"
share|improve this answer
add comment

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.

share|improve this answer
add comment

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.
share|improve this answer
2  
Are you sure this is code trolling? This looks like an actual solution. –  Joe Z. 18 hours ago
 
I prefer System.out.println(sentence); for the purpose of complexity. –  Anony-Mousse 12 hours ago
add comment

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)))
share|improve this answer
add comment

C

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, r, backslash, and then n: (or "\r\n").

(Interesting historical note: on older Macintoshes it was a different sequence of four characters: "\n\r"... 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:

"foo\nbaz\nbar"

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 slash 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
              - bump index by 2 to skip both backslash and n */
           putc(10, stdout);
           i += 2;
       } else {
           /* This position didn't match the pattern for a newline
              - print character with printf
              - bump index by 1 to go to next matchable position */
           printf("%c", buffer[i]);
           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!

foo
baz
bar

\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. Did you think putc ran more than once? :-)

Even global variables and returning an error code, for good measure...

share|improve this answer
add comment
from random import randint

def splitstring(s):
    while len(s):
        n=randint(2,20)
        yield s[:n]
        s=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.

share|improve this answer
add comment

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")
share|improve this answer
 
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 yesterday
 
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. –  crazedgremlin yesterday
 
It might help to add a few comments below your code. –  Christopher Creutzig yesterday
2  
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! –  Anony-Mousse 12 hours ago
add comment

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:\>
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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