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\$
7
  • 1
    \$\begingroup\$ Is this a popularity-contest or code-golf? \$\endgroup\$
    – osvein
    Dec 30, 2013 at 22:55
  • \$\begingroup\$ @user1981338, neither, read the wiki of the code-trolling tag. \$\endgroup\$
    – Turion
    Dec 31, 2013 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\$ Jan 8, 2014 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, 2014 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, 2014 at 12:54

44 Answers 44

48
votes
\$\begingroup\$

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

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

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

\$\endgroup\$
3
  • 11
    \$\begingroup\$ Return 1 for success. Glorious. \$\endgroup\$
    – Turion
    Dec 30, 2013 at 18:29
  • 3
    \$\begingroup\$ Awsome to the max :) \$\endgroup\$
    – Johannes
    Jan 1, 2014 at 22:34
  • 3
    \$\begingroup\$ Damn this one is pure evil. \$\endgroup\$ Jan 4, 2014 at 12:05
32
votes
\$\begingroup\$
  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.

\$\endgroup\$
4
  • \$\begingroup\$ I tried not working... \$\endgroup\$
    – rakeshNS
    Jan 1, 2014 at 7:17
  • 30
    \$\begingroup\$ I got "Exception: Unsafe operation. Do not run with scissors" \$\endgroup\$
    – Paul
    Jan 5, 2014 at 10:58
  • 1
    \$\begingroup\$ My rock crushed the scissors! D'oh! \$\endgroup\$
    – bobbel
    Apr 9, 2014 at 12:03
  • \$\begingroup\$ My scissors accidentally cut the instructions...Seg fault? \$\endgroup\$ Apr 11, 2014 at 14:03
30
votes
\$\begingroup\$

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.

\$\endgroup\$
2
  • \$\begingroup\$ Try to do it in one line, for extra credits!!!1! \$\endgroup\$ Dec 29, 2013 at 22:41
  • \$\begingroup\$ 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! \$\endgroup\$ Jan 16, 2014 at 4:49
27
votes
\$\begingroup\$

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)
\$\endgroup\$
1
  • 2
    \$\begingroup\$ Wow!!! That's soooo evil....I want to vote twice!!!!!!!! \$\endgroup\$ Jan 8, 2014 at 17:57
11
votes
\$\begingroup\$

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 = sys.stdin.read()
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.

\$\endgroup\$
8
votes
\$\begingroup\$

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)
        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)
        split_into_lines = IO.File.ReadLines(temp_file_name)
    End Function
End Module
\$\endgroup\$
1
  • 9
    \$\begingroup\$ Every VB introduction should be firmly founded in a solid understanding of monads! \$\endgroup\$ Dec 28, 2013 at 20:22
5
votes
\$\begingroup\$

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
\$\endgroup\$
5
votes
\$\begingroup\$

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);
\$\endgroup\$
2
  • 2
    \$\begingroup\$ It is wonderful how Python makes it automagically readable. \$\endgroup\$
    – Turion
    Dec 29, 2013 at 14:35
  • \$\begingroup\$ Wait, no #defines? ;-) \$\endgroup\$ Dec 29, 2013 at 22:44
4
votes
\$\begingroup\$

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!
\$\endgroup\$
4
  • 1
    \$\begingroup\$ your SplitStr always splits by newlines no matter what the argument is, not sure if intentional \$\endgroup\$
    – mniip
    Dec 29, 2013 at 11:19
  • \$\begingroup\$ @mniip, that's a beautiful bug. "we need infinity for this to work" \$\endgroup\$
    – Turion
    Dec 29, 2013 at 14:36
  • \$\begingroup\$ It is totally intentional. \$\endgroup\$
    – user11485
    Dec 29, 2013 at 18:17
  • \$\begingroup\$ Infinite (lazy) ranges are a really neat trick, I just HAD to put it in there. \$\endgroup\$
    – user11485
    Dec 29, 2013 at 18:18
4
votes
\$\begingroup\$

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

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 ' or ,
\$\endgroup\$
5
  • \$\begingroup\$ Love this one. What language even is that? \$\endgroup\$
    – Turion
    Dec 28, 2013 at 19:09
  • \$\begingroup\$ @Tur Haha, forgot that sorry.it's Ruby. Will edit \$\endgroup\$
    – Doorknob
    Dec 28, 2013 at 19:09
  • \$\begingroup\$ @Turion: Appears to be Ruby. \$\endgroup\$
    – 0..
    Dec 28, 2013 at 19:09
  • \$\begingroup\$ (Shame on me Python-centered person) \$\endgroup\$
    – Turion
    Dec 28, 2013 at 19:12
  • 3
    \$\begingroup\$ I see variable names like that on a daily basis... \$\endgroup\$
    – Bojangles
    Dec 29, 2013 at 19:34
4
votes
\$\begingroup\$

C++

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!
            ++numberOfSplitsInTheInput;
        }
    }

    // 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') {
            ++i;
        }
        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';

            splits.erase(result);
        }
    }

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

    system("PAUSE");

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

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)

\$\endgroup\$
2
  • 2
    \$\begingroup\$ I guess OP will reject it seeing the output \$\endgroup\$
    – Wasi
    Dec 28, 2013 at 18:40
  • 1
    \$\begingroup\$ @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. \$\endgroup\$ Dec 28, 2013 at 22:38
3
votes
\$\begingroup\$

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

\$\endgroup\$
2
  • \$\begingroup\$ Haha, reads great, but what is this split function you use at the end? \$\endgroup\$
    – Turion
    Dec 28, 2013 at 18:41
  • \$\begingroup\$ @Turion The last line is a overly complicated way of saying string.split('/n'); to confuse the theoretical student :). \$\endgroup\$
    – C1D
    Dec 28, 2013 at 18:44
3
votes
\$\begingroup\$

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;
            }
        }
    }
}
\$\endgroup\$
4
  • \$\begingroup\$ I really, really hope I don't see this one in production. It's unfortunately plausible though. \$\endgroup\$ Dec 28, 2013 at 22:41
  • \$\begingroup\$ @dawnail333: And other answers are more production ready? This only has one serious bug (that I'm aware of) :-) \$\endgroup\$
    – poke
    Dec 28, 2013 at 23:42
  • \$\begingroup\$ @poke, other that the input string may not contain commas? \$\endgroup\$
    – Turion
    Dec 29, 2013 at 14:33
  • \$\begingroup\$ @Turion: The no-commas-in-the-input bug is the only one I'm aware of. \$\endgroup\$
    – poke
    Dec 29, 2013 at 19:49
3
votes
\$\begingroup\$

C++

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.

\$\endgroup\$
3
votes
\$\begingroup\$

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
        else:
            # 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?

Explanation

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

\$\endgroup\$
3
votes
\$\begingroup\$

Objective LOLCODE

HAI
CAN HAZ STDIO?
    AWSUM THX
        VISIBLE "Split\nString"
        KTHX
    O NOES
        BTW //Error check
        KTHX
KTHXBYE
\$\endgroup\$
0
2
votes
\$\begingroup\$

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

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

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/qfaiwHoG4Utef6D8VdE1S+XTtQiudG1Jm2i3v02Bj2w3Tntu2k9hXeK1DTW4ElFIDS0AFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFJmgBaTNNL1Tv8AUrTTLR7q+uYbW3QfNLM4RR+JoAulhUUs8cMTSSyIkajLMxwFHqSa5i38TXfiBA3h2yJtGGRqV8jRxMPWOPh5O3Pyrz949KZceDrLU3Euvz3essDkRXDlbdT7QphePVtx9zR6gVL/AOL3gvT5mhOrm4K8M1rA8qD/AIEBj8q1fD3j/wANeJ5/s+l6kklxjcIJEaNyB3AYDP4VbjgsdPtPJhtbe0tlH3FiWNAPoABXk/jPVPA8Wt6dHoFhDc+JRfQvG+k4QAhwSHZ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KM0AFFGaM0AFFGaKACiiigAooozQAUhGaXNGaAGbBRsFPooATaKWjNGaACijNFABRRRmgAoozRmgAoozRmgAoozRQAUUUUAFFKaSgAoxRRQAYoxRRQAUUUUAFFFFABRiiigAxRiiigAooooAKMUUUAGKKKKACjFFFABijFFFABijFFFABiiiigAooooAU0lBooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigBTSc0GjNABzRzRRQAc0c0UUAHNHNFGaADmjmjNFABzRzRRQAc0c0ZooAOaOaM0ZoAOaOaKKADmjmiigA5o5oozQAc0c0ZozQAc0c0ZooAOaOaKKADmjmjNGaAFpMUtFACYoxS0UAJijFLRQAmKMUtFACYoxS0UAJijFLRQAmKMUtFACYoxS0UAJijFLRQAmKMUtFACUUtFACYoxS0UAJijFLRQAmKMUtFACYoxS0UAf/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
\$\endgroup\$
2
votes
\$\begingroup\$
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.

\$\endgroup\$
2
  • \$\begingroup\$ Fun, but I did specify where I want the string to be split. \$\endgroup\$
    – Turion
    Dec 31, 2013 at 14:33
  • \$\begingroup\$ I originally read the question as "split the string by some criteria and print each part on a new line". \$\endgroup\$
    – nitro2k01
    Dec 31, 2013 at 14:46
2
votes
\$\begingroup\$

Python

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
        try:
            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"
        else:
            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)
    input()
\$\endgroup\$
2
votes
\$\begingroup\$

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:

Java

String result = input.split("\n|\r\n");

PHP

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

Java

String result = input.split("(?m)^");

PHP

$result = preg_split('/^/m', $input);

Note that there is an extra empty string entry in front, just remove it or loop from index 1.


Explanation

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!
\$\endgroup\$
1
vote
\$\begingroup\$

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 ~]$
\$\endgroup\$
1
vote
\$\begingroup\$

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]);
}
\$\endgroup\$
1
vote
\$\begingroup\$

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);
    }
}
\$\endgroup\$
1
vote
\$\begingroup\$

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 (
        String.join("",
          Pattern.compile("[nN][eE][wW] [lL][iI][nN][eE]")
              .splitAsStream(STRING_TO_SPLIT)
              .map((s) -> s + "\n")
              .collect(() -> new ArrayList<>(),
                    (c, e) -> c.add(e), (c1, c2) -> c1.addAll(c2))));

  }
}
\$\endgroup\$
1
vote
\$\begingroup\$

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

Output:

Hello world!

\$\endgroup\$
1
vote
\$\begingroup\$

Php

<? Spliter($yourstring); ?>

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

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

\$\endgroup\$
1
vote
\$\begingroup\$

bash specific

There is a great job for !

Yes, splitting string could by done in really simple way:

string=$'foo\nbar\nbaz'

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

limitA=0

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
do
    addr=${hexline%% *}
    hexline="${hexline#$addr}"
    addr=$((16#$addr))
    for field in $hexline
    do
        if [ "$field" = "0a" ]
        then
            lines+=( "${string:limitA:addr-limitA}" )
            limitA=$(( addr + 1 ))
        fi
        ((addr++))
    done
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++ ))
do
    echo ${lines[idx]}
done

Putting all this in one script:

#!/bin/bash

string=$'this is a very long string containing spaces\nshorted, but containing comas...\nthird line.'
declare -a lines
limitA=0
while read hexline
do
    addr=${hexline%% *}
    hexline="${hexline#$addr}"
    addr=$((16#$addr))
    for field in $hexline
    do
        if [ "$field" = "0a" ]
        then
            lines+=( "${string:limitA:addr-limitA}" )
            limitA=$(( addr + 1 ))
        fi
        ((addr++))
    done
done < <(od -A x -t x1 <<<"$string")

for (( idx=0 ; idx < ${#lines[@]} ; idx++ ))
do
    echo $idx: ${lines[idx]}
done

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:

#!/bin/bash

string=$'foo\nbar\nbaz'
declare -a lines
limitA=0
for (( idx=0 ; idx < ${#string} ; idx++ ))
do

    if [ "${string:idx:1}" = $'\n' ]
    then

        lines+=( "${string:limitA:idx-limitA}" )
        limitA=$(( idx + 1 ))
    fi
done
lines+=( "${string:limitA}" )

for (( idx=0 ; idx < ${#lines[@]} ; idx++ ))
do
    echo ${lines[idx]}
done

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:

#!/bin/bash

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:

#!/bin/bash

echo $'foo\nbar\nbaz'

will give same result.

\$\endgroup\$

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