text:
Implement the Universal Machine emulator
The goal is to write a full program that emulates the Universal Machine from ICFP 2006 with the shortest code. The Universal Machine has a very simple instruction set explained here. The emulator has to read a filename from command-line argument, and run the file as the program, so your language has to support command-line arguments and stdin/out in some way. The emulator has to complete the sandmark within a reasonable time (not decades).
Here's a short explanation of the instruction set:

The machine has eight registers each holding an 32-bit unsigned integer.
  The machine holds an indexed set of arrays of 32-bit unsigned integer cells.
  Shortly speaking, the allocation instruction returns an opaque 32-bit uint which is the handle to the created array, which has a static size, and holds 32-bit uint elements.
  The 0'th array denotes the program. It is loaded from a big-endian file on startup.
  There is also an Instruction Pointer which points to a cell in the 0 array.
  On each step, an instruction is read from the cell the Pointer points to, and the Pointer is inceremented before anything is done.
  The 4 most significant bits represent the opcode.
  If the opcode is 13, then the next 3 bits represent the register, and the other 25 represent the number that is written into the said register.
  Otherwise the 9 least significant bits represent three registers, say, A, B, and C, where C is represented by the 3 least significant bits.
  Then depending on the opcode, the following happens:
  0. A = B unless C == 0
  1. A = B[C]
  2. A[B] = C
  3. A = B + C
  4. A = B * C
  5. A = B / C
  6. A = ~(B & C)
  7. The emulator exits
  8. B = allocate(C)
  9. deallocate(C)
  10. output a character from C to stdout
  11. input a character from stdin into C
  12. copy the array B into the 0 array and set the Pointer to C

I have written a needlessly complex but totally fast implementation (ab)using x86_64 jitted assembly (the fun starts in emit()), which would for sure help you if you misunderstand some of the Machine's aspects.

You have to decide if this should be code-golf or popularity-contest. They are exclusive.

If I'm not mistaken, the machine is described as being Big Endian, not Little Endian.

@Hasturkun d'oh I always mess these up, I keep thinking  Big Endian stands for "ending in the bigger byte"

Can you clarify how the arrays are accessed? with instruction 1., A=B[C] is B an array or the 3-bit value from the instruction used as an index, or an opaque identifier value returned from instruction 8?

@luserdroog Well that is just a short explanation, I suggest you reat the manual as well. P.S: I added some explanation into the question

The sandmark program is actually pretty amazing. It self-decompresses before executing. Elsewhere on http://www.boundvariable.org/ there are *.um files which are not compressed.

@mniip Big Endian and Little Endian are terms borrowed from Gulliver's Travels. The small people of Lilliput were at war with the small people of Blefuscu, because the Lilliputians were "Big Endians" who believed you should eat the big end of a boiled egg first, and the Blefuscans believed the reverse. The original Gulliver's Travels was a serious novel by Jonathan swift. The author was commenting on the stupidity of going to war over political and religious differences. Gulliver was forced to leave after being charged with treason for refusing to help out in the war.

PHP: 443 416  384 bytes
<?php @eval(ereg_replace('[U-Z]','$\0',strtr('for(Y=[unpack("N*",join(file($argv[1])))];;A|=0){{W=Y[V=0][++U]
C&&A=B
A=Y[B][C+1]
Y[A][B+1]=C
A=B+C
A=B*C
A=bcdiv(PB),PC))*1
A=~B|~C
die
B=++Z
unset(Y[C])
echo chr(C)
C=fgetc(STDIN);C=ord(C)-(C=="")
Y[0]=Y[B|0];U=C
X[W>>25&7]=W&33554431;}}',['
'=>';}if((W>>28&15)==V++){',A=>'X[W>>6&7]',B=>'X[W>>3&7]',C=>'X[W&7]',P=>'sprintf("%u",'])));

*Revamped again*. It's as small as I can possibly get it now. I kept some variables down the far end of the alphabet so that the regex that inserts the $ signs doesn't mangle the STDIN constant, so here's a little glossary:

U: instruction pointer
V: index of opcode that's currently being tested
W: current instruction word
X: the 8 general purpose registers
Y: main memory (each block is 1-based, since that's how unpack() returns arrays)
Z: id of next free memory block (will eventually overflow, but the sandmark only uses ~92 million)
A,B,C are the registers of the current instruction as in the spec

Unsigned division is a subtle nuisance (the *1 is needed to ensure that large numbers cast back to the correct int) but the rest of the arithmetic is easy to keep 32-bit by ORing the arithmetic register with 0 (A|=0) after each instruction.

I found this project really interesting but striving to minimize the character count made it slow and inelegant, so I also made a simple (not golfed) Java version, that can complete the sandmark in a few minutes instead of taking all day:
import java.io.*;
import java.util.HashMap;

public class UniversalMachine {
    public static void main(String[] args) throws IOException {
        if (args.length == 0) {
            System.err.println("Program not specified.");
            System.exit(1);
        }

        int[] program;
        try (RandomAccessFile raf = new RandomAccessFile(args[0], "r")) {
            program = new int[(int)(raf.length() / 4)];
            for (int i = 0; i < program.length; i++) {
                program[i] = raf.readInt();
            }
        }

        HashMap<Integer,int[]> memory = new HashMap<>();
        memory.put(0, program);
        int nextMemKey = 1;

        int[] R = new int[8]; // Registers
        int IP = 0; // Execution Finger (Instruction Pointer)

        loop: for (;;) {
            int ins = program[IP++];
            int op = ins >>> 28;
            if (op == 13) { // Orthography
                int A = (ins >> 25) & 7;
                int num = ins & 0x01FF_FFFF;
                R[A] = num;
            } else {
                final int A = (ins >> 6) & 7;
                final int B = (ins >> 3) & 7;
                final int C = (ins >> 0) & 7;
                switch (op) {
                case 0: // Conditional Move
                    if (R[C] != 0) R[A] = R[B];
                    break;
                case 1: // Array Index
                    R[A] = memory.get(R[B])[R[C]];
                    break;
                case 2: // Array Amendment
                    memory.get(R[A])[R[B]] = R[C];
                    break;
                case 3: // Addition
                    R[A] = R[B] + R[C];
                    break;
                case 4: // Multiplication
                    R[A] = R[B] * R[C];
                    break;
                case 5: // Division
                    R[A] = (int)((R[B] & 0xFFFF_FFFFL) / (R[C] & 0xFFFF_FFFFL));
                    break;
                case 6: // Not-And
                    R[A] = ~(R[B] & R[C]);
                    break;
                case 7: // Halt
                    break loop;
                case 8: // Allocation
                    // note: must use C before setting B, as they may be the same reg
                    memory.put(nextMemKey, new int[R[C]]);
                    R[B] = nextMemKey++;
                    break;
                case 9: // Abandonment
                    memory.remove(R[C]);
                    break;
                case 10: // Output
                    System.out.print((char)R[C]);
                    break;
                case 11: // Input
                    R[C] = System.in.read();
                    break;
                case 12: // Load Program
                    IP = R[C];
                    if (R[B] != 0) {
                        memory.put(0, program = memory.get(R[B]).clone());
                    }
                    break;
                }
            }
        }
    }
}

i don't think you need to adjust result of division to 32 bits because it is always smaller-than-or-equal-to the dividend, which is adjusted already

Just out of curiosity, what does it look like ungolfed?

@mniip It's a bit differently laid out now, but I do need to be careful with division because during the division the numbers are unsigned, and at every other moment they're signed.

Perl, 407
It looks like the question might seem too complex, actually it's very simple.
I'm still very new to perl though, anyway here it is
open$f,shift;binmode$f;push@{$m[0]},unpack'N',$b while read$f,$b,4;$z=2**32;while(){$o=$m[0][$p++];$a=\$r[$o>>6&7];$b=\$r[$o>>3&7];$c=\$r[$o&7];eval qw,$$a=($$b)if$$c $$a=$m[$$b][$$c] $m[$$a][$$b]=$$c $$a=($$b+$$c)%$z $$a=$$b*$$c%$z $$a=$==$$b/$$c $$a=$$b&$$c^($z-1) exit $$b=scalar@m;$m[$$b]=[] undef$m[$$c] print(chr$$c) $$c=ord(getc) $m[0]=[@{$m[$$b]}]if$$b;$p=$$c $r[$o>>25&7]=$o&33554431,[$o>>28].";";}

It runs really slow, probably 800x slower than the JITed x86_64 one.
Also, a friend of mine made a reference C implementation

Is this a problem in the reference C code?: if(((Memory[++PC]>>28)&15) == 13) {  Registers[(Memory[PC]>>25)&7] = (Memory[PC]&0x01ffffff); the instruction isn't cached, so any opcodes not 13 would pre-execute the next instruction, no?

C, 924 838 825 696 646 623
I store a "pointer" (byte-offset) in the register designated b in the instruction, and use whatever register designates an array in the pseudocode in the same manner (or reverse, rather, to reconstitute a pointer) to access that array later. Still need to try the test program...
Edit: added comments.
Edit: fixed instruction 12. change the pointer, not the instruction in memory. Count is with all comments, indents, and newlines removed.
Edit: It appears to be running now, assuming I'm interpreting the results correctly. :) The final realization was that the 0 array is indeed referenced by the handle 0, which may be found in an uninitialized register. A very twisted little machine! :)
Edit: rewrote debugging apparatus to use write instead of printf.... The idea here is to remove bugs. :) Edit: putchar() and getchar() are also no-nos with sbrk. It now works, and appears quite fast.
#define O(_)*a=*b _*c;B
#define B break;case
#define U unsigned
U*m,r[8],*p,*z,f,x,*a,*b,*c;main(int n,char**v){U char
u[4];z=m=p=sbrk(4);f=n>1?open(v[1],0):0;\
while(read(f,u,4)){*m++=(((((*u<<8)|u[1])<<8)|u[2])<<8)|u[3];sbrk(4);}sbrk(4);\
for(;x=*p++,1;){c=r+(x&7);b=r+((x>>3)&7);a=r+((x>>6)&7);switch(x>>28){case
0:*c?*a=*b:0;B
1:*a=(*b?m+*b:z)[*c];B
2:(*a?m+*a:z)[*b]=*c;B
3:O(+)4:O(*)5:O(/)6:*a=~(*b&*c);B
7:return 0;case
8:*b=1+(U*)sbrk(4*(1+*c))-m;(m+*b)[-1]=*c;B
9:B
10:*u=*c;write(1,u,1);B
11:read(0,u,1);*c=*u;B
12:*b?memcpy(z=sbrk(4*(m+*b)[-1]),m+*b,4*(m+*b)[-1]):0;p=&z[*c];B
13:a=r+((x>>25)&7);*a=x&0x1ffffff;}}}

For little-endian only, there's a 611 character version.
#define O(_)*a=*b _*c;B
#define B break;case
#define U unsigned
U*m,r[8],*p,*z,f,x,*a,*b,*c;main(int n,char**v){U char
u[4];z=m=p=sbrk(4);f=n>1?open(v[1],0):0;while(read(f,u,4)){*m++=(((((*u<<8)|u[1])<<8)|u[2])<<8)|u[3];sbrk(4);}sbrk(4);for(;x=*p++,1;){c=r+(x&7);b=r+((x>>3)&7);a=r+((x>>6)&7);switch(x>>28){case
0:*c?*a=*b:0;B
1:*a=(*b?m+*b:z)[*c];B
2:(*a?m+*a:z)[*b]=*c;B
3:O(+)4:O(*)5:O(/)6:*a=~(*b&*c);B
7:return 0;case
8:*b=1+(U*)sbrk(4*(1+*c))-m;(m+*b)[-1]=*c;B
9:B
//10:*u=*c;write(1,u,1);B //generic
10:write(1,c,1);B //little-endian
//11:read(0,u,1);*c=*u;B //generic
11:read(0,c,1);B //little-endian
12:*b?memcpy(z=sbrk(4*(m+*b)[-1]),m+*b,4*(m+*b)[-1]):0;p=&z[*c];B
13:a=r+((x>>25)&7);*a=x&0x1ffffff;}}}

Indented and commented, with (extended) commented debugging apparatus.
//#define DEBUG 1
#include <fcntl.h> // open
#include <signal.h> // signal
#include <stdio.h> // putchar getchar
#include <string.h> // memcpy
#include <sys/types.h> // open
#include <sys/stat.h> // open
#include <unistd.h> // sbrk read
unsigned long r[8],*m,*p,*z,f,x,o,*a,*b,*c; // registers memory pointer zero file working opcode A B C
char alpha[] = "0123456789ABCDEF";
//void S(int x){signal(SIGSEGV,S);sbrk(9);} // autogrow memory while reading program
void writeword(int fd, unsigned long word){
    char buf[8];
    unsigned long m=0xF0000000;
    int off;
    for (off = 28; off >= 0; m>>=4, off-=4) {
        buf[7-(off/4)]=alpha[(word&m)>>off];
    }
    write(fd, buf, 8);
    write(fd, " ", 1);
}
int main(int n,char**v){
#ifdef DEBUG
    int fdlog;
#endif
    unsigned char u[4]; // 4-byte buffer for reading big-endian 32bit words portably
    int cnt;

#ifdef DEBUG
    fdlog = open("sandlog",O_WRONLY|O_CREAT|O_TRUNC, 0777);
#endif
    z=m=p=sbrk(4); // initialize memory and pointer
    //signal(SIGSEGV,S); // invoke autogrowing memory -- no longer needed
    f=n>1?open(v[1],O_RDONLY):0; // open program
    while(read(f,u,4)){ // read 4 bytes
        *m++=(((((*u<<8)|u[1])<<8)|u[2])<<8)|u[3]; // pack 4 bytes into 32bit unsigned in mem
        sbrk(4); // don't snip the end of the program
    }
    sbrk(4);
    for(cnt=0;x=*p++,1;cnt++){ // working = *ptr; ptr+=1
        c=r+(x&7); // interpret C register field
        b=r+((x>>3)&7); // interpret B register field
        a=r+((x>>6)&7); // interpret A register field
#ifdef DEBUG
        {int i;write(fdlog,"{",1);for(i=0;i<8;i++)writeword(fdlog, r[i]);
            write(fdlog,"} ",2);
        }
        write(fdlog, alpha+(x), 1);
        write(fdlog, alpha+(x>>28), 1);
#endif
        switch(o=x>>28){ // interpret opcode
            case 0:
#ifdef DEBUG
                write(fdlog, "if(rX)rX=rX\n", 12);
#endif
                *c?*a=*b:0;
                break; // Conditional Move A=B unless C==0
            case 1:
#ifdef DEBUG
                write(fdlog, "rX=rX[rX]\n", 10);
#endif
                *a=(*b?m+*b:z)[*c];
                break; // Array Index A=B[C]
            case 2:
#ifdef DEBUG
                write(fdlog, "rX[rX]=rX\n", 10);
#endif
                (*a?m+*a:z)[*b]=*c;
                break; // Array Amendment A[B] = C
            case 3:
#ifdef DEBUG
                write(fdlog, "rX=rX+rX\n", 9);
#endif
                *a=*b+*c;
                break; // Addition A = B + C
            case 4:
#ifdef DEBUG
                write(fdlog, "rX=rX*rX\n", 9);
#endif
                *a=*b**c;
                break; // Multiplication A = B * C
            case 5:
#ifdef DEBUG
                write(fdlog, "rX=rX/rX\n", 9);
#endif
                *a=*b/ *c;
                break; // Division A = B / C
            case 6:
#ifdef DEBUG
                write(fdlog, "rX=~(rX&rX)\n", 12);
#endif
                *a=~(*b&*c);
                break; // Not-And A = ~(B & C)
            case 7:
#ifdef DEBUG
                write(fdlog, "halt\n", 5);
#endif
                return 0; // Halt
            case 8:
#ifdef DEBUG
                write(fdlog, "rX=alloc(rX)\n", 13);
#endif
                *b=1+(unsigned long*)sbrk(4*(1+*c))-m;
                   (m+*b)[-1]=*c;

                   break; // Allocation B = allocate(C)
            case 9:
#ifdef DEBUG
                   write(fdlog, "free(rX)\n", 9);
#endif
                   break; // Abandonment deallocate(C)
            case 10:
#ifdef DEBUG
                   write(fdlog, "output(rX)\n", 11);
#endif
                   //putchar(*c);
                   //*u=u[1]=u[2]=' ';
                   u[3]=(char)*c;
                   write(fileno(stdout), u+3, 1);
                   break; // Output char from C to stdout
            case 11:
#ifdef DEBUG
                   write(fdlog, "rX=input()\n", 11);
#endif
                   //x=getchar();*c=x;
                   read(fileno(stdin), u+3, 1);
                   *c=u[3];
                   break; // Input char from stdin into C
            case 12:
#ifdef DEBUG
                   write(fdlog, "load(rX)[rX]\n", 13);
#endif
                    *b?memcpy(z=sbrk(4*(m+*b)[-1]),m+*b,4*(m+*b)[-1]):0;
                    p=&z[*c];
                    break; // Load Program copy the array B into the 0 array, Ptr=C
            case 13:
#ifdef DEBUG
                    write(fdlog, "rX=X\n", 5);
#endif
                    a=r+((x>>25)&7);*a=x&0x1ffffff; // Orthography REG=immediate-25bit
        }
    }
}

Array handles are 100% opaque. No matter what you pass it, the program is supposed to use the same value when accessing arrays. P.S. i just tried compiling it, you're missing a couple includes. P.P.S. did you ever compile it? what's lbreak and how can you unary-* an int

Yes. A little too eager. :) Updated code compiles with gcc on Cygwin.

@mniip So it's only array 0 that's designated by "number"?

just compiled it, it only executes 2 instructions out of sandmark: d000108f c0000030 and then exits

I fixed one bug. It executes 7 instructions now before halting.

Instruction 12 refers to an array handle in B, which is register 6, which has not been loaded. Does that mean the 0 array remains where it is and the pointer is adjusted to offset C? I've got a binary dump in the chatroom.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
How do I split a string??? Help plz? (code trolling)
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.

Is this a [tag:popularity-contest] or [tag:code-golf]?

@user1981338, neither, read the wiki of the code-trolling tag.

Here's a valuable resource I found regarding string splitting... I hope you find it useful!
http://bit.ly/1dSklhO

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.

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

Thanks for your input, @Turion! As I said, this post is... different - it does have many votes, but the community wants (in the poll and as expressed in chat) it to be deleted, as it is very underspecified. If you'd like, you can join us in chat now to discuss this.

After further consideration, according to input in chat and on meta, this post is being locked instead.

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)

Return 1 for success. Glorious.

Awsome to the max :)

Damn this one is pure evil.

Grab a scissor and the string you want to split.
Open the scissor.
Put your string between the scissor blades.
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.

I tried not working...

I got "Exception: Unsafe operation. Do not run with scissors"

My rock crushed the scissors! D'oh!

My scissors accidentally cut the instructions...Seg fault?

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.

Try to do it in one line, for extra credits!!!1!

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!

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)

Wow!!! That's soooo evil....I want to vote twice!!!!!!!!

This can be done in a few lines of code by the following simple algorithm:

Look for the first newline character in the string.
Append the part up to the newline to a list.
Remove the part up to the newline from the string.
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.

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

Every VB introduction should be firmly founded in a solid understanding of monads!

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

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

It is wonderful how Python makes it automagically readable.

Wait, no #defines? ;-)

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 ,

Love this one. What language even is that?

@Tur Haha, forgot that sorry.it's Ruby. Will edit

@Turion: Appears to be Ruby.

(Shame on me Python-centered person)

I see variable names like that on a daily basis...

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!

your SplitStr always splits by newlines no matter what the argument is, not sure if intentional

@mniip, that's a beautiful bug. "we need infinity for this to work"

It is totally intentional.

Infinite (lazy) ranges are a really neat trick, I just HAD to put it in there.

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.

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

Haha, reads great, but what is this split function you use at the end?

@Turion The last line is a overly complicated way of saying string.split('/n'); to confuse the theoretical student :).

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

I really, really hope I don't see this one in production. It's unfortunately plausible though.

@dawnail333: And other answers are more production ready? This only has one serious bug (that I'm aware of) :-)

@poke, other that the input string may not contain commas?

@Turion: The no-commas-in-the-input bug is the only one I'm aware of.

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)

I guess OP will reject it seeing the output

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

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.

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.

#define statements don't exist in python!
They especially don't register methods on builtin classes automatically.
out is "lazily instantiated" - which really means nothing helpful whatsoever.
The provided function would include the separator in the result.
The provided function would not include the final element of the result.
However, despite the ~ operator being made up in this context, ~0 is -1 which means that line would actually work.
The returns are messed up. The actual place it would return just returns without a value.
Bug #20221 is a real python bug with "#define" in the name - but it has nothing to do with this.
The input line can only be a single line... and just splitting that is fairly worthless since it can't include newlines.
Usage of sys.stdout.write(str(x)) instead of print(x) is a bad way to do things.
"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.

Objective LOLCODE
HAI
CAN HAZ STDIO?
    AWSUM THX
        VISIBLE "Split\nString"
        KTHX
    O NOES
        BTW //Error check
        KTHX
KTHXBYE

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

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.

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.

Fun, but I did specify where I want the string to be split.

I originally read the question as "split the string by some criteria and print each part on a new line".

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

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'
[encoded data, 7792 characters]
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

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!

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 ~]$

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

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

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

  }
}

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!

bash specific
There is a great job for bash!
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 bash 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.

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

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

I may be missing something, but how is this code trolling? Apart from being slightly convoluted with the head (reverse x), of course.

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.

It might help to add a few comments below your code.

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!

Perl
Replace the "any text to split \n next line\n another line" (without quotes) with the text you want to split:
#!/usr/bin/perl -w

my @array = split("\n", "any text to split \n next line\n another line");
print "@array";

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

Java
public static String[] splitOnNewlines(String str)
{
    ByteArrayInputStream bais = new ByteArrayInputStream(str.getBytes());
    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.

Golf-Basic 84
i`Od`O

The right tool for the job!

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

Java
This is a very hard problem (NP Complete in fact). However there exists a recursive solution :
public String[] split(String str) {
  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;
      }
    }
  }
}

Java
In Java you can achieve that by just 2 lines of code
sentence="What ever your sentence is, it comes here";
String [] splitSentence=sentence.split("\n");
        for(String s:splitSentence)
        System.out.println(s);// print it or do what ever you want to do with that. Now s contains you'r splited String.

Are you sure this is code trolling? This looks like an actual solution.

I prefer System.out.println(sentence); for the purpose of complexity.

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

#include<string>
#include<iostream>
using namespace std;
int main()
{
    string outputArray[100];
    string temp = "";
    int count = 0;
    string inputString = "a\na\na"; // inputString

    for(int i=0;i<inputString.length();i++)
    {
        if(inputString[i] == '\n')
        {
            outputArray[count++] = temp;
            temp = "";
        }
        else
        {
            temp += inputString[i];
        }
    }
    outputArray[count++] = temp;
// to print outputArray
    for(int i=0;i<count;i++)
    {
        cout<<outputArray[i]<<endl;
    }
    return 0;
}

The strings are stored in outArray.

Trollpost, JavaScript
(and yes, trolling on a code-trolling question ;-)
function splitOnEveryNewLine(string) {
  return string.split('\n');
}

Why not use a predefined function?

The other answers may work, but they only work on 8 bits at a time! These days characters can be 32 bits. The following code should be much faster because it works on 32bits.
It is also designed to use plain arithmetic without conditionals so a decent optimising compiler should be able to replace this with 128bit SIMD operations! (I bet you thought your computer could only do 64bits)
#include <signal.h>
#include <string.h>
#include <stdio.h>
#include <stdint.h>

char *mystring;

void aftersplit(int i) {
    printf("Split!\n");
    // In C arrays start with 0, so *mystring[0] is the first split string
    printf("Size of strings: %d, %d\n",strlen(&mystring[0]),strlen(&mystring[1]));
    exit(0); // This will exit out of the while loop
}

void main(int argc, char **argv){
    //Allocate some memory and put "Split[NEWLINE]Str!" in it;
    mystring=strcpy(malloc(16),"Split\nStr!\n");
    //"char" is a misnomer, actually Unicode characters are up to 32bit
    //But char is only 8bits!!! Operating on 32bits can be up to 4 times
    //faster, so we cast mystring to 32bits.
    uint32_t *str32=(uint32_t*)mystring;

    //Use of branches can greatly slow down modern processors.
    //We avoid having any branches in our code by asking the OS to call
    // "aftersplit" after we have processed
    //past the end of the segment containing mystring.
    printf("%d\n", '\n\n\n\n');
    signal(SIGSEGV,aftersplit);

    printf("Size of string: %d\n",strlen(mystring));

    //while(1) avoids any branches. Novice programmers may think this would
    //loop forever, but remember that "aftersplit" will eventually be called.
    int i=0;while(1){
            //In C '0' terminates the string, so if we cancel out newlines
            //To get 0 this will split the string

        //Since we are using 32 bit we can process 8 bytes at once.
        //gcc will generate a warning, but that is only because the
        //order isn't defined. Here all the characters are '\n' so the
        //order doesn't matter.
        str32[i]-='\n\n\n\n';
        i++;
    }
}

What I have said above is true and it... works... but there are some important facts left out:

The "Segment containing the string" contains all the mutable program data, so we trash memory. Getting a SIGSEGV signal isn't a way of detecting the end of a string.
The resulting strings are unrecognisable since we have subtracted '\n' from each character.
the resulting mystring is not an array of strings. The only reason mystring[1] has the the length of the second string is because it is one less than the length of the first string. The second string is actually (mystring+strlen(mystring)+1).

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

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

output=""
while read input
do output="$output$the_delimiter$input"
done
echo $output

The beautiful thing about Unix is that you can pass data to your program through the standard putting stream.
So if you save the above program as string_splitter.sh and make it executable, then you can run:
$ cat list_of_files | ./string_splitter.sh

or even get advanced:
$ ls /a/folder | ./string_splitter.sh

Voila, your list of files will be handily split by space characters!
Don't worry about any filenames in your list which might containing spaces - Unix doesn't allow them anyway.
If you don't want that pesky newline at the end of the output, there is a built-in feature for that.  Just put -n as the first item in your list.
Trolling

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

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

Python
split = []
line = ''
count = 0
for char in string:
    count = count + 1
    if char != '\n':
        line = line + char
        if count == len(string):
            split.append(line)
    else:
        split.append(line)
        line = ''

Make sure that you append after the string length has been met otherwise you'll be missing part of the assignment.
It should work like this:
X:\>python troll_char.py
the quick brown fox
jumped over the lazy dog
and ate the programmer

['the quick brown fox', 'jumped over the lazy dog', 'and ate the programmer']

X:\>

Python
from sys import stdout as o
i=raw_input("Give me string plz? ")
for x in i+"\n": o.write(x) if x!="\n" else o.write("\n")

please read the description of the tag.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Swap contents of two files
This is a code-golf question.  You need to take the contents of two separate files (i.txt and o.txt) and swap them.  You can create a third file to help you with the process, but have your program delete it after the file contents are swapped.  Renaming the files is now allowed again.
Programs must work for any file content.
Shortest code wins, all eligible submissions will be up-voted.

Rename the files. No need to "take the contents" and swap them to achieve the result.

@Darren Stone I think that should be illegal.  Thanks for catching that before answers were submitted.

Looks like a bad constraint, renaming is the best way to do this

Alright, I can remove this constraint.

@hdante but 'renaming files' is not exchanging their contents. On a system that uses inodes the goal here would be for i.txt's inode to contain the data from o.txt's inode, and vice versa, so that if there are hardlinks to those inodes elsewhere, their contents will appear swapped as well. Renaming can't accomplish that.

zsh, 20 + 4 = 24
The script needs to be named .txt.
(mv [io]$0;>i$0)<o$0

or 14 with parameters:
(mv $@;>$1)<$2

I like the one without a temporary file better, though: i=`<i.txt`;<o*>i*;<<<$i>o*. It’s too bad this has to be shorter.

Rules changed to allow renaming files.  You can update your code if you wish.

You could save 3 chars by replacing <t>o*;rm t by mv t o* !

@F.Hauri: Ah, thanks! (There were rules against renaming at one point.)

This code is not correct. It works only in the special case where i* and o* will match only i.txt and o.txt respectively, i.e. there is no other file with a name beginning with either "i" or "o".

@ErwanLegrand, that’s not really a special case. Just make a new directory. Alternatively, if what Darren Stone used below is allowed (which it is, according to the asker), simply exchange for $1 and $2.

Python, 77
import os;t='.txt';r,i,o,x=[os.rename,'i'+t,'o'+t,'1'+t];r(i,x);r(o,i);r(x,o)

Python, 65
import os;t='.txt'
for a,b in zip('iox','xio'):os.rename(a+t,b+t)

Python, 63
import os;t='.txt'
for a,b in 'ix','oi','xo':os.rename(a+t,b+t)

PHP, 68
<?$r=rename;$t='.txt';$r("i$t","x");$r("o$t","i$t");$r("x","o$t");?>

Windows Batch File, 42
move i.txt x&move o.txt i.txt&move x o.txt

Windows Batch File (args), 30
move %1 x&move %2 %1&move x %2

I didn't know you can use $r=rename to create aliases to functions in PHP. Thanks!

Two bash based answers; 52 and 62 chars
shell: diff + patch (+ tee + sed...) 52
Maybe not the shorter, but I find this fun (and there is no use of temporary file):
diff -u [io]*|tee >(patch -r -)|sed 1s/i/o/|patch -R

Where content is swapped and files are modified in place:
Sample run
swapContent() { diff -u $1 $2|tee >(patch -r -)|sed 1s/$1/$2/|patch -R ;}

while read page file ;do man -Pcol\ -b $page >$file.txt;done <<<$'man i\nbash o'
printf "%s %8d  %s\n" $(join -j 2 <(stat -c '%s %n' [io]*) <(md5sum [io]*))
swapContent [io]*
printf "%s %8d  %s\n" $(join -j 2 <(stat -c '%s %n' [io]*) <(md5sum [io]*))

Could produce something like:
i.txt    46007  1da1f7533e0eab1e97cce97bb7ca1d3b
o.txt   321071  7dcd230890faf4ef848d4745eda14407
patching file o.txt
i.txt   321071  7dcd230890faf4ef848d4745eda14407
o.txt    46007  1da1f7533e0eab1e97cce97bb7ca1d3b

use of xargs to simplify mv requests
Not as funny, but nice anyway.
set -- {i,o}.txt t&&eval 'xargs -n2 mv<<<"' \${1,3,2,1,3,2} \"

Nota: As first patch output is not redirected, they become garbage on second patch command. This is the reason because only one patching file o.txt appear.

PHP, 89
I thought I'd give it a shot.
<?php $f1='f1.txt';$f2='f2.txt';$ft='ft.txt';copy($f1,$ft);copy($f2,$f1);rename($ft,$f2);

Ungolfed version:
<?php
$f1 = 'f1.txt';
$f2 = 'f2.txt';
$ft = 'ft.txt';

copy($f1, $ft);
copy($f2, $f1);
rename($ft, $f2);

Apparently I took 2 answers of here and combined them.. oh well.

VBA (148...132) and (126...110)
Renaming with a temp file t in the c:\ drive. Also first attempt at golf :S
Sub s():Set f=CreateObject("Scripting.FileSystemObject"):i="c:\i.txt":t="c:\t":f.MoveFile i,t:f.MoveFile "c:\o.txt",i:Kill t:End Sub

If scrrun.dll is referenced already, could cut it down a bit to 126...110.
Sub s():Set f=new FileSystemObject:i="c:\i.txt":t="c:\t":f.MoveFile i,t:f.MoveFile "c:\o.txt",i:Kill t:End Sub

Looks like your code has a lot of whitespace. Are you sure they are needed? You can have a much better score if you remove them.

I don't think it's needed the editor just threw it in. Removed apart from where it's necessary :)

Ruby, 72 bytes
Wow! A Ruby code golf! I don't think that's ever been attempted before!
In all reality though, this required some nice Ruby shortcuts and a couple patterns which I found. It was my first golf ever and it was very fun to do. Without further ado, here's the golfed code:
3.times{|x|x*=2;t=".txt";a=([?i,?a,?o]*2);File.rename(a[x]+t,a[x+1]+t)}

And the ungolfed version
3.times do |x|
    x = x * 2
    t=".txt"
    a=([?i,?a,?o]*2)
    File.rename(a[x]+t, a[x+1]+t)}
end

The key factor in this is that the parameters passed to the File.rename are this, exactly:
File.rename "i.txt", "a.txt"
File.rename "o.txt", "i.txt"
File.rename "a.txt", "o.txt"

Hope this (doesn't) make sense!

Powershell, 44 49 bytes
$t='.txt'
ren i$t a$t -fo
ren o$t i$t
ren a$t o$t

where ren is alias for Rename-Item. The script uses and delete a third file a.txt.

This can fail with certain encoding. Because gc default is UTF8NoBOM but sc default is ASCII. Try some UTF-8 files or binary files and you can see how it can fail.

Indeed. Thanks. It need -e by -n parameters to ensure that the files unchanged. It would be nice to add a parameter -readCount 0 to performance. The script with rename is shorter :) Fixed.

05AB1E --no-lazy, 39 37 35 bytes
-2 thanks to Kevin Cruijssen.
'°ŽDÀøεS’.í¼t"’«`’File.‚™‚ˆ"ÿ,"ÿ’.E

Try it online! Link includes a header and footer to create the files and prove that it worked.
'°ŽDÀøεS’...’«`’...’.E  # trimmed program
      ε                 # for each in...
     ø                  # all characters of...
'°Ž                     # "bio"...
     ø                  # paired with corresponding characters of...
'°ŽD                    # "bio"...
    À                   # rotated left one character...
                    .E  # evaluate...
               ’...’    # "File.rename\"ÿ\",\"ÿ\""...
                        # (implicit) with the first ÿ replaced by...
              `         # second element of...
       S                # list of characters of...
                        # (implicit) current element...
                        # (implicit) with each element...
             «          # concatenated with...
        ’...’           # ".txt"...
                        # (implicit) with the second ÿ replaced by...
              `         # first element of...
        S               # list of characters of...
                        # (implicit) current element...
                        # (implicit) with each element...
              «         # concatenated with...
         ’...’          # ".txt"...
                    .E  # as Elixir code

====================

File.rename  # full program
File.rename  # rename file with name argument 1 to argument 2

Nice answer! vy can be ε for -1. Also, í¼t and ‚™ can simply be txt and re; the dictionary string and hard-coded string are the same byte-count. Try it online.

Oh, and ’.txt’ can be ’.txt"’, allowing you to drop the " after both ÿ for another -1: try it online - 35 bytes

Ruby
i1="i.txt"
i2="o.txt"
c1=IO.readlines(i2)
c2=IO.readlines(i1)
File.open(i1){|x|x.puts(c1)}
File.open(i2){|x|x.puts(c2)}

Shortened version:
a=["i.txt","o.txt"]
(0..1).each{|x|b[x]=IO.readlines(a[x])*"\n"}
a.reverse!
(0..1).each{|x|IO.write(a[x],b[x])}

Not the shortest, but very simple and easy to read. Also, no intermediate files, only RAM.

Given that it’s a [tag:code-golf], you could at least take out the spaces and try somewhat for the shortest.

Totally didn't realize it was code-golf, sorry

Shell script, 24
Works in Bash and probably most shells.  Pass with your two filenames as parameters.
mv $1 ੴ;mv $2 $1;mv ੴ $2

If you want fixed filenames then this will do it, for a 12 char penalty:
mv i.txt ੴ;mv o.txt i.txt;mv ੴ o.txt

@minitech, yes it does. 'ੴ' becomes 'o.txt'.  Those are mv operations, not cp.

Second best answer so far!  Reduce it by two characters and you win! I do not care about fixed filenames.

Python:
import os
l,e='i_o'*2,'.txt'
for x,y in zip(l,l[1:])[::2]:
 os.rename(x+e,y+e)

C 162
Golfed: uses t.txt as tmp file and swaps names then removes t.txt.
#include <stdio.h>
#define R(x,y) rename(x,y)
#define X(x) remove(x)
int main(){char *i="i.txt",*o="o.txt",*t="t.txt";R(i,t);X(i);R(o,i);R(t,o);X(t);return 0;}

Edit: removed 2 spaces

PHP - 172
Golfed version of @EisaAdil's answer
$f1='file1.txt';$f2='file2.txt';$f1contents=file_get_contents($f1);$f2contents=file_get_contents($f2);file_put_contents($f1,$f2contents);file_put_contents($f2,$f1contents);

PHP, 45
<?php
copy('i','t');copy('o','i');rename('t','o');

Not very golfy but shortest PHP so far.

file extensions are missing.

Rebol - 46 (rename file) or 55 (r/w contents)
Rename file (using t as temporary file):
r: :rename
r i: %i.txt %t
r o: %o.txt i
r %t o

Read in then write out file contents:
a: read i: %i.txt
b: read o: %o.txt
write o a
write i b

Groovy - 99 chars
This is my attempt, with Groovy 2.2.1. I tried to do it without renaming:
f={new File(it+".txt")}
w={x,y->x.withWriter{it.write y}}
i=f "i"
o=f "o"
t=i.text
w i,o.text
w o,t

Ungolfed:
file = { new File(it+".txt") }
writeTextToFile = { x,y -> x.withWriter{it.write y} }

iFile = file("i")
oFile = file("o")

iText = iFile.text
writeTextToFile (iFile,oFile.text)
writeTextToFile (oFile,iText)

C: 65 characters
#define r(a,b)rename(#a".txt",#b".txt");
main(){r(i,)r(o,i)r(,o)}

A quite simple solution in C that does the job. It uses a temporary name (.txt) for one of the files before giving it its proper new name.
Ungolfed (note how the syntax highlighting fails in the define, a bug has been uncovered!):
#include <stdio.h>

#define r(a, b) rename(#a ".txt", #b ".txt");

int main()
{
    r(i,  ) // rename("i.txt",  ".txt");
    r(o, i) // rename("o.txt", "i.txt");
    r( , o) // rename( ".txt", "o.txt");

    return 0;
}

Perl, 120 bytes (Contents swapping without file renaming)
use open IO,':bytes';undef$/;open I,"<i.txt";$I=<I>;open I,"<o.txt";open O,">i.txt";print O<I>;open O,">o.txt";print O$I

The file contents is put into memory and written back to the other file. Thus i.txt and o.txt must fit into memory.
Since the file contents are actually exchanged, hard links are updated automatically, see AJManfield's comment.
Ungolfed:
use open IO => ':bytes'; # binmode, not needed for Unix, but needed for Windows
undef $/;                # read whole file instead of lines
open I, "<i.txt";        # open i.txt for reading
$I = <I>;                # read i.txt
open I, "<o.txt";        # open o.txt for reading
open O, ">i.txt";        # open i.txt for writing
print O <I>;             # read o.txt and put the contents in i.txt
open O, ">o.txt";        # open o.txt for writing
print O $I;              # write o.txt with contents of old i.txt

Windows Batch File (48)
type i.txt>a&type o.txt>i.txt&type a>o.txt&del a

I forgot about the move command when I wrote this...

You just overwrote my a file!

@Danny The question states that you may create another file, but it must be deleted.

Windows Batch, 39 bytes
ren i.txt x&ren o.txt i.txt&ren x o.txt

Tcl, 122 bytes
set A [read [open i.txt]]
puts [set i [open i.txt w]] [read [open o.txt]]
puts [set o [open o.txt w]] $A
close $i
close $o

Try it online!

Tcl, 169 bytes
set A [read [set i [open i.txt r]]]
set B [read [set o [open o.txt r]]]
close $i
close $o
puts [set i [open i.txt w]] $B
puts [set o [open o.txt w]] $A
close $i
close $o

Try it online!

Lua, 71 70 bytes
_ENV=os t='.txt'i,o,r='i'..t,'o'..t,rename r(i,t)r(o,i)r(t,o)remove(t)

Try it online!
Define os, the operating system library, as the global table so we can write rename and remove instead of os.rename and os.remove. (Incidentally this also means the one-letter variables are actually fields in the os table.) Make short alias for os.rename to save some space. Set up filename variables, using '.txt' as temporary file. Do the renaming and deleting.

PHP, 52 bytes
AsksAnyway´s php modernized & golfed:
($r=rename)(i.$e=".txt",x);$r(o.$e,i.$e);$r(x,o.$e);

Run with php -nr '<code>'.

AWK, 66 bytes
a=FILENAME,b=!b?a:b{c[a]=c[a]$0RS}END{printf c[a]>b;printf c[b]>a}

Try it online!
Note: I provided a TIO line, but I have no idea how to make it work when the code needs to read from input files?
The rename approaches seem to be much shorter, but here's one in AWK that copies the data instead.  At a high level, it takes a commandline like,
gawk '...code...' i.txt o.txt

which feeds both files into the program on STDIN. It uses the magic variable FILENAME to cache the contents of each one into a separate entry in an associative array.  Then the END clause just overwrites each file with the content from the other one.
The "test" per line, which is always truthy, sets a to the current filename over and over.  And it also ensures b is to the first filename seen.
a=FILENAME,b=!b?a:b

The code block executed per line, just appends the current line to the accumulated data for the current filename.
c[a]=c[a]$0RS

Then once all the lines from both files have been read, the END code block writes out the files with the content swapped.
printf c[a]>b;printf c[b]>a

SmileBASIC, 36 35 bytes
@L
RENAME@OI[2-I],@IO[I]I=I+1GOTO@L

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/