On some terminals, pressing backspace generates the control code ^H to delete the previous character. This gave rise to a snarky idiom where edits are feigned for comedic effect:

Be nice to this fool^H^H^H^Hgentleman, he's visiting from corporate HQ.

Given a string with one or more ^H's, output the result of backspacing on each ^H. The input will use only printable characters (ASCII 32-126), and ^ will only appear as ^H. Backspaces will never happen on empty text.

You may not assume that the output environment supports control codes, in particular the backspace code \x08.

>> Horse^H^H^H^H^HCow

>> Be nice to this fool^H^H^H^Hgentleman, he's visiting from corporate HQ.
Be nice to this gentleman, he's visiting from corporate HQ.

>> 123^H45^H^H^H78^H

>> Digital Trauma^H^H^H^H^H^H^H^H^H^H^H^H^H^HMaria Tidal Tug^H^H^H^H^H^H^H^H^H^H^H^H^H^H^HDigital Trauma
Digital Trauma


Here's a by-language leaderboard, courtesy of Martin Büttner.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

# Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

# Ruby, <s>104</s> <s>101</s> 96 bytes

function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/52946/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){$.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:true,success:function(e){answers.push.apply(answers,e.items);if(e.has_more)getAnswers();else process()}})}function shouldHaveHeading(e){var t=false;var n=e.body_markdown.split("\n");try{t|=/^#/.test(e.body_markdown);t|=["-","="].indexOf(n[1][0])>-1;t&=LANGUAGE_REG.test(e.body_markdown)}catch(r){}return t}function shouldHaveScore(e){var t=false;try{t|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(n){}return t}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading);answers.sort(function(e,t){var n=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0],r=+(t.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0];return n-r});var e={};var t=1;answers.forEach(function(n){var r=n.body_markdown.split("\n")[0];var i=$("#answer-template").html();var s=r.match(NUMBER_REG)[0];var o=(r.match(SIZE_REG)||[0])[0];var u=r.match(LANGUAGE_REG)[1];var a=getAuthorName(n);i=i.replace("{{PLACE}}",t++ +".").replace("{{NAME}}",a).replace("{{LANGUAGE}}",u).replace("{{SIZE}}",o).replace("{{LINK}}",n.share_link);i=$(i);$("#answers").append(i);e[u]=e[u]||{lang:u,user:a,size:o,link:n.share_link}});var n=[];for(var r in e)if(e.hasOwnProperty(r))n.push(e[r]);n.sort(function(e,t){if(e.lang>t.lang)return 1;if(e.lang<t.lang)return-1;return 0});for(var i=0;i<n.length;++i){var s=$("#language-template").html();var r=n[i];s=s.replace("{{LANGUAGE}}",r.lang).replace("{{NAME}}",r.user).replace("{{SIZE}}",r.size).replace("{{LINK}}",r.link);s=$(s);$("#languages").append(s)}}var QUESTION_ID=45497;var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:&lt;(?:s&gt;[^&]*&lt;\/s&gt;|[^&]+&gt;)[^\d&]*)*$)/;var NUMBER_REG=/\d+/;var LANGUAGE_REG=/^#*\s*((?:[^,\s]|\s+[^-,\s])*)/
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
<script src=https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js></script><link rel=stylesheet type=text/css href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id=answer-list><h2>Leaderboard</h2><table class=answer-list><thead><tr><td></td><td>Author<td>Language<td>Size<tbody id=answers></table></div><div id=language-list><h2>Winners by Language</h2><table class=language-list><thead><tr><td>Language<td>User<td>Score<tbody id=languages></table></div><table style=display:none><tbody id=answer-template><tr><td>{{PLACE}}</td><td>{{NAME}}<td>{{LANGUAGE}}<td>{{SIZE}}<td><a href={{LINK}}>Link</a></table><table style=display:none><tbody id=language-template><tr><td>{{LANGUAGE}}<td>{{NAME}}<td>{{SIZE}}<td><a href={{LINK}}>Link</a></table>

  • 4
    \$\begingroup\$ Is AAA^HB^H^H valid? \$\endgroup\$ – Nathan Merrill Jul 10 '15 at 21:47
  • \$\begingroup\$ @NathanMerrill Yes, and it results in A. \$\endgroup\$ – xnor Jul 10 '15 at 21:54
  • 3
    \$\begingroup\$ I suspect retina would do well here. \$\endgroup\$ – Claudiu Jul 10 '15 at 21:55
  • 1
    \$\begingroup\$ @Fatalize: "Backspaces will never happen on empty text." \$\endgroup\$ – Maltysen Jul 10 '15 at 22:06
  • 16
    \$\begingroup\$ @Maria Tidal Tug comes back to haunt me \$\endgroup\$ – Digital Trauma Jul 10 '15 at 23:18

41 Answers 41


GNU sed, 11 bytes


Test output:

$ echo "Horse^H^H^H^H^HCow
Be nice to this fool^H^H^H^Hgentleman, he's visiting from corporate HQ.
Digital Trauma^H^H^H^H^H^H^H^H^H^H^H^H^H^HMaria Tidal Tug^H^H^H^H^H^H^H^H^H^H^H^H^H^H^HDigital Trauma" | sed ':;s/.^H//;t'
Be nice to this gentleman, he's visiting from corporate HQ.
Digital Trauma
  • 5
    \$\begingroup\$ Look who showed up! It's Maria Tidal Tug^H^H^H^H^H^H^H^H^H^H^H^H^H^H^HDigital Trauma! \$\endgroup\$ – Alex A. Jul 13 '15 at 18:43
  • \$\begingroup\$ @AlexA. Am I missing an in-joke? \$\endgroup\$ – user253751 Jul 14 '15 at 1:59
  • \$\begingroup\$ @immibis: See Digital Trauma's comment on the question. \$\endgroup\$ – Alex A. Jul 14 '15 at 2:01
  • \$\begingroup\$ sed -r ':;s/(^|.)\^H//;t' - this works at expense of extra 6 bytes \$\endgroup\$ – aragaer Jul 15 '15 at 10:40
  • \$\begingroup\$ @aragaer Why is that necessary? The OP says "Backspaces will never happen on empty text". I think a ^H the beginning of the string is a backspace on empty text. \$\endgroup\$ – Digital Trauma Jul 15 '15 at 15:05

Pyth, 11 bytes



               Implicit: z = input()
      cz"^H    z.split("^H")
.U             reduce, with the first element of the list as the initial value.
   Pb          Remove the last character of what we have so far.
  +  Z         And add on the next segment.
               Print implicitly.

Gema, 6 bytes


Sample run:

bash-4.3$ gema -p '?#\^H=' <<< 'pizza is alright^H^H^H^H^H^Hwesome'
pizza is awesome

CW, because the fool vs. gentleman example takes far too long. (Killed after a day. Maybe a glitch in the interpreter? All other examples here are processed in fractions of seconds.) Gema's recursive pattern not seems to be affected by the recursion level, but the amount of non-matching text increases processing time exponentially.

  • \$\begingroup\$ Is there a link to the language? A quick search on Github turned up quite a few \$\endgroup\$ – Sp3000 Jul 11 '15 at 10:29
  • \$\begingroup\$ Sure. gema.sourceforge.net (BTW, the Gema project was registered 2003-10-27, while GitHub was launched 2008-04-10. That may be a reason to not find it there.) \$\endgroup\$ – manatwork Jul 11 '15 at 10:32
  • \$\begingroup\$ I believe the recursion depth is equally to the length of the non-matching string, because it will recurse again and again until the \^H maches, matching one character at a time to the ?. \$\endgroup\$ – isaacg Jul 11 '15 at 22:11

C, 52 bytes


We define a function f that takes a pointer to the string as input. After the function call, that pointer will contain a modified string.

A simple test:

int main(int argc, char** argv) {
    char buf[300] = "Digital Trauma^H^H^H^H^H^H^H^H^H^H^H^H^H^HMaria Tidal Tug^H^H^H^H^H^H^H^H^H^H^H^H^H^H^HDigital Trauma";
    return 0;

The above prints:

Digital Trauma
  • 1
    \$\begingroup\$ This was really clever. A couple things I noticed: globals are already initialized to zero, so no need to init j in your for loop (of course then it's single use, but I don't see anything about that in the rules :) ). You can also combine the assignment with the decrement: j;f(char*s){for(;s[j]==94?*s--=s[j],j+=3:s++);} (47 bytes) \$\endgroup\$ – Cole Cameron Jul 11 '15 at 3:46
  • \$\begingroup\$ @ColeCameron you missed this \$\endgroup\$ – undergroundmonorail Jul 11 '15 at 3:56
  • \$\begingroup\$ @undergroundmonorail dang, I was just double checking to see if I missed that. I'm still new to code golf but I'll remember that for the future :). Thanks for the info! \$\endgroup\$ – Cole Cameron Jul 11 '15 at 4:02
  • 1
    \$\begingroup\$ @ColeCameron That has an unsequenced modification and access (UB), and causes an immediate EXC_BAD_ACCESS on my compiler/machine, unfortunately. \$\endgroup\$ – BrainSteel Jul 11 '15 at 14:51
  • 1
    \$\begingroup\$ @Quentin I tried that, but because of the comma in s--, j+=3 and operator precedence, it doesn't work right. \$\endgroup\$ – BrainSteel Jul 12 '15 at 20:36

Haskell, 47 bytes

h(a,_:_:b)=f$init a++b;h(x,_)=x

Defines a function f :: String -> String. How it works:

    f "ab^Hc^Hd"
=== h ("ab", "^Hc^Hd")   (find ^H)
=== f ("a" ++ "c^Hd")    (backspace)
=== f "ac^Hd"            (join)
=== h ("ac", "^Hd")      (find ^H)
=== f ("a", "d")         (backspace)
=== f "ad"               (join)
=== h ("ad", "")         (find ^H)
=== "ad"                 (no ^H: base case)
  • 1
    \$\begingroup\$ I think you can save a byte by swapping the two cases of h and doing h(x,_)=x for the empty string case. \$\endgroup\$ – Zgarb Jul 13 '15 at 7:17

CJam, 14 13 bytes


How it works

q                   e# Read the entire input
 "^H"/              e# Split it on occurrences of string "^H"
      {    }*       e# Reduce on the split array
       W\t          e# This is the tricky part. We know that if there are two parts that we
                    e# are reducing on, they must be separated by "^H". Which in turn means
                    e# that from the first part, last characters needs to be deleted
                    e# So we simply put the second part in place of the last character of the
                    e# first part.
          s         e# Doing the above makes it a mixed array of character and string.
                    e# So we convert it to a single string, ready to be served as first part
                    e# in next reduce iteration

UPDATE: 1 byte saved thanks to jimmy23013

Try it online here

  • 2
    \$\begingroup\$ 1 byte shorter: W\ts. \$\endgroup\$ – jimmy23013 Jul 10 '15 at 22:43

Retina, 13 bytes



The two lines should go to their own files but you can run the code as one file with the -s flag.

At each step we delete the first match for .\^H in the string. We repeat this (with the + modifier) until no deletion happens.

  • \$\begingroup\$ Just a curiosity: why the capturing of (.*), as it seems to be just put back unchanged? \$\endgroup\$ – manatwork Jul 11 '15 at 11:21
  • 1
    \$\begingroup\$ @manatwork This way we only capture the first .\^H in one step. Otherwise abc^H^H^H would result in ab^ after the first step. \$\endgroup\$ – randomra Jul 11 '15 at 11:55
  • 4
    \$\begingroup\$ Apologies for not implementing a replacement limit yet (which would probably allow something like +1`.\^H). ;) \$\endgroup\$ – Martin Ender Jul 11 '15 at 12:19

JavaScript (ES6), 39 bytes




Test=_=>(Out(I.value + "\n-> " + f(I.value)),I.value='')

,"Be nice to this fool^H^H^H^Hgentleman, he's visiting from corporate HQ."
,"Digital Trauma^H^H^H^H^H^H^H^H^H^H^H^H^H^HMaria Tidal Tug^H^H^H^H^H^H^H^H^H^H^H^H^H^H^HDigital Trauma"]
.forEach(t => Out(t + "\n-> " + f(t)))
#I { width:400px }
<pre id=O></pre>
<input id=I><button onclick='Test()'>-></button>


Perl, 20 16 15 bytes

(14 characters code + 1 character command line option.)


Sample run:

bash-4.3$ perl -pe 's/.\^H//&&redo' <<< "Be nice to this fool^H^H^H^Hgentleman, he's visiting from corporate HQ."
Be nice to this gentleman, he's visiting from corporate HQ.
  • 1
    \$\begingroup\$ Save 4 characters: 1while s/.\^H// \$\endgroup\$ – Kevin Reid Jul 11 '15 at 14:48
  • \$\begingroup\$ Wow! That's great @KevinReid. Thank you. \$\endgroup\$ – manatwork Jul 11 '15 at 15:00
  • 1
    \$\begingroup\$ One more: s/.\^H//&&redo \$\endgroup\$ – Dennis Jul 11 '15 at 19:12
  • \$\begingroup\$ Thank you, @Dennis. redo somehow not made its way into my skill set. Will have to change that. \$\endgroup\$ – manatwork Jul 12 '15 at 9:33
  • 2
    \$\begingroup\$ Note that @Dennis's version will only work (as intended) if it's the only statement inside a loop or a { } block. (The reason why it works with perl -p is that the -p switch automatically wraps your code inside a while loop.) Kevin's version works in any setting. \$\endgroup\$ – Ilmari Karonen Jul 12 '15 at 10:29

Julia, 58 42 41 bytes

Saved 16 bytes thanks to manatwork and 1 thanks to Glen O!


This creates a recursive function that accepts a string and returns a string.

This replaces one occurrence of ^H at a time with an empty string while the input contains ^.


julia> f("123^H45^H^H^H78^H")

julia> f("pizza is alright^H^H^H^H^H^Hwesome")
"pizza is awesome"
  • \$\begingroup\$ This is the first time I've seen Julia in the wild. Nice! \$\endgroup\$ – Ogaday Feb 9 '16 at 16:27

REGXY, 10 bytes

Uses REGXY, a regex substitution based language. Replaces any character followed by ^H with nothing. The second line then executes which is just a pointer to the previous line, repeating the substitution until it fails to match.


This compiles and executes correctly with the sample interpreter in the link above, but the solution is perhaps a bit cheeky as it relies on an assumption in the vagueness of the language specification. The spec states that the first token on each line (before the /) acts as a label, but the assumption is that a null label-pointer will point back to the first command in the file with a null label (or in other words, that 'null' is a valid label). A less cheeky solution would be:


Which amounts to 13 bytes.


Python 3, 53 bytes

for x in input().split("^H"):o=o[:-1]+x

But personally I like this wordier version better:


The interesting thing is that


actually works and gives 'Back', so I tried to map ^H -> [:-1] and any other char c -> 'c' then eval, but unfortunately you can't have any strings afterwards without a +, so this fails:

  • \$\begingroup\$ Heyy... that's pretty neat. \$\endgroup\$ – Alex Van Liew Nov 17 '15 at 21:53
  • \$\begingroup\$ +=works in the loop \$\endgroup\$ – CalculatorFeline Apr 11 '16 at 5:30
  • \$\begingroup\$ @CatsAreFluffy It's o=o[:-1]+x, not o=o+x \$\endgroup\$ – Sp3000 Apr 11 '16 at 5:36
  • \$\begingroup\$ Oops, missed that. Does something like o[:-2]=x work? \$\endgroup\$ – CalculatorFeline Apr 11 '16 at 16:50
  • \$\begingroup\$ @CatsAreFluffy You can't assign to str \$\endgroup\$ – Sp3000 Apr 11 '16 at 16:53

Haskell, 52 47 bytes

import Data.Lists

Usage example:

> map (foldl1((++).init).splitOn"^H") ["Horse^H^H^H^H^HCow", "123^H45^H^H^H78^H", "Digital Trauma^H^H^H^H^H^H^H^H^H^H^H^H^H^HMaria Tidal Tug^H^H^H^H^H^H^H^H^H^H^H^H^H^H^HDigital Trauma"]
["Cow","17","Digital Trauma"]

How it works:

                  splitOn"^H"     -- split on substring "^H", e.g "Horse^H^H^H^H^HCow" -> ["Horse","","","","","Cow"]
                 .                -- then
foldl1(         )                 -- fold from left by
            init                  --   first dropping the last char from the left argument
       (++).                      --   second concatenating left and right argument

Ruby, 27 24 20 bytes

(19 characters code + 1 character command line option.)


Thanks to:

  • Ventero for suggesting to use the global variables (-4 characters)

Sample run:

bash-4.3$ ruby -pe '$_=$`+$'"'"'while/.\^H/' <<< "Be nice to this fool^H^H^H^Hgentleman, he's visiting from corporate HQ."
Be nice to this gentleman, he's visiting from corporate HQ.
  • \$\begingroup\$ +1 I thought I'd do a Ruby answer until I saw this -- I'm pretty sure this is as small as it's gonna get. Great usage of []! \$\endgroup\$ – daniero Jul 11 '15 at 14:21
  • \$\begingroup\$ There was another version in the beginning: loop{$_[/.\^H/]=""}rescue"" This one is nicer as it demonstrates Ruby's exception handling coolness. \$\endgroup\$ – manatwork Jul 11 '15 at 14:30
  • \$\begingroup\$ Haha, that's a great one :) \$\endgroup\$ – daniero Jul 11 '15 at 14:45
  • 1
    \$\begingroup\$ Better late than never: $_=$`+$'while~/.\^H/ for 20 (you can even drop the tilde if you don't care about the regexp literal in condition warning). \$\endgroup\$ – Ventero Apr 10 '16 at 21:44
  • 1
    \$\begingroup\$ @manatwork: Technically it appears in all ruby versions >= 1.9 (regex and string literals in conditions were deprecated after 1.8), I guess your ruby simply still defaults 1.8, whereas irb uses ruby 2.1.5. \$\endgroup\$ – Ventero Apr 11 '16 at 20:03

Python 2, 50

It's a bit odd having a second lambda in there, but seems to be the best Python so far.

lambda s:reduce(lambda a,b:a[:-1]+b,s.split('^H'))

Pyth - 19 bytes

Reduce works really, really well with this but it only does one char at a time so I had to spend almost as many chars as the actual algo to do a replace ^H with linebreak. Looking for a better way to do that.


Try it online here.


TeaScript, 7 bytes [Not competing]

Not competing as TeaScript was made after this challenge was posted. This is here as reference.


This uses the new TeaScript 3, and recursive replaces to remove the characters

  • 1
    \$\begingroup\$ For some reason this counts as 8859 bytes on the leaderboard because of the ISO 8859 link... \$\endgroup\$ – ev3commander Dec 16 '15 at 22:54
  • \$\begingroup\$ regerence? xD \$\endgroup\$ – cat Apr 10 '16 at 20:41

K5, 64 bytes

K isn't really designed for this kind of work...


golflua, 36 bytes

\f(s)@o!=s o=s;s=s:g(".^H","",1)$~s$

Sample run:

Lua 5.2.2  Copyright (C) 1994-2013 Lua.org, PUC-Rio
> \f(s)@o!=s o=s;s=s:g(".^H","",1)$~s$
> w(f("Be nice to this fool^H^H^H^Hgentleman, he's visiting from corporate HQ."))
Be nice to this gentleman, he's visiting from corporate HQ.

Javascript, 62 bytes

Not the shortest one, but works fine.


This probably can be shortened a lot!

  • 1
    \$\begingroup\$ Not the shortest one and does not work eiither (try any of the test cases). The regexp should not be global (remove /g) \$\endgroup\$ – edc65 Jul 11 '15 at 17:29
  • \$\begingroup\$ @edc65 Thanks for the tip. I tried some things and they worked. That's why I posted like that \$\endgroup\$ – Ismael Miguel Jul 11 '15 at 21:29

R, 54 52 bytes


Same basic idea as my Julia answer. This creates a recursive function that accepts a string and returns a string. If the input is equal to itself with a single occurrence of ^H removed, return it, otherwise call the function again.

You can try it online!


ECMAScript 6, 57 bytes

s=>{while(~s.indexOf`^H`)s=s.replace(/.\^H/,'');return s}

This is probably golfable, just gotta think of a way probably not

  • 2
    \$\begingroup\$ How about s=>{while(s!=(s=s.replace(/.\^H/,""));return s}? \$\endgroup\$ – lrn Jul 11 '15 at 12:41
  • \$\begingroup\$ Or, if while and return are too long, it could be recursive: var f=s=>s==(s=s.replace(/.\^H/))?s:f(s) \$\endgroup\$ – lrn Jul 11 '15 at 14:31
  • \$\begingroup\$ @lm you should add the second parameter "" for replace. Then you have my answer :) \$\endgroup\$ – edc65 Jul 11 '15 at 17:24
  • \$\begingroup\$ True. And the empty string argument needs to be there, I must have copied the wrong version :( \$\endgroup\$ – lrn Jul 11 '15 at 23:14
  • \$\begingroup\$ ~s.indexOf`^H` can become /\^H/.test(s) \$\endgroup\$ – Not that Charles Nov 18 '15 at 4:53

Java, 78 77 bytes

String f(String a){while(!a.equals(a=a.replaceFirst(".\\^H","")));return a;}
  • 1
    \$\begingroup\$ You can remove the space after the comma to save one char. \$\endgroup\$ – ProgramFOX Jul 13 '15 at 6:51

(Visual)FoxPro any version 80 bytes

DO WHILE AT('^H',t)>0
t = STRT(t,SUBS(t,AT('^H',t)-1,3))

Repeating string translation to empty by finding ^H and backing up one character.


Julia, 41 39 bytes


What it's doing is using ^H as a delimiter, and then removing the last character on each string then concatenating the next string before removing the last character again. Unlike the other Julia answer, this is not a recursive function.

Note: I've removed the function name from the definition. Originally, it said f(s)= rather than s->, and you used it as f("AAA^HB^H^H")... but I'm saving two bytes by letting it be "anonymous", and use itself as its name. You use it like this:


(you can also assign a variable to it as f=s->foldl((t,v)->chop(t)v,split(s,"^H")), then f("AAA^HB^H^H") will work)


rs, 8 bytes

Technically, this doesn't count, as it depends on a feature I added after this question was posted. However, I think it's pretty neat.


Live demo and test cases.

  • \$\begingroup\$ Is the new feature a limit replacement? \$\endgroup\$ – xnor Jul 23 '15 at 4:55
  • \$\begingroup\$ @xnor Yes: the ?1. \$\endgroup\$ – kirbyfan64sos Jul 23 '15 at 12:54
  • \$\begingroup\$ @Optimizer Why? You're losing to Gema anyway. :O \$\endgroup\$ – kirbyfan64sos Jul 23 '15 at 13:00
  • \$\begingroup\$ Yeah :( . Saw gema after posting comment \$\endgroup\$ – Optimizer Jul 23 '15 at 13:03

Python 2, 74 + 2 = 76 Bytes

I've tried a few approaches so far, this is the best I've been able to come up with so far.

for l in n:d=l=='^';o=[o+l*(1-c),o[:-1]][d];c=d
print o
  • 4
    \$\begingroup\$ Where are those 2 extra bytes coming from? \$\endgroup\$ – xnor Jul 11 '15 at 9:17
  • \$\begingroup\$ @xnor input has to be surrounded by quotes for this to work. I forgot to put that in the post. \$\endgroup\$ – Kade Jul 11 '15 at 13:42
  • 1
    \$\begingroup\$ I think the usual convention has been to allow string arguments to be taken in quotes for free, but I'm not totally sure. \$\endgroup\$ – xnor Jul 13 '15 at 7:19

Mumps, 84 Bytes

R Z S T="",Y=$L(Z,"^H") F I=1:1:Y{S T=T_$P(Z,"^H",I) S:I<Y T=$E(T,1,$L(T)-1)} W !,T

This could probably be made shorter as a function (1 byte I was able to save in quick testing) but I kinda like the one-liner aspect... :-)

The braces come from the Intersystems Cache flavour of Mumps which is what I'm most versed in.


Java - 123 bytes

I personally like the g---1 part the best.

String f(char[] a){String b="";for(int g=-1;++g<a.length;b=(a[g++]=='^'?b.substring(0,b.length()-1):b+a[g---1]));return b;}

expanded (slightly):

  String f(char[] a) {
      String b = "";
      for (int g = -1;
           ++g < a.length;
           b = (a[g++]=='^' 
                ? b.substring(0, b.length() - 1) 
                : b + a[g---1])
      return b;

Batch - 138 bytes

@!! 2>nul||cmd/q/v/c%0 %1&&exit/b
set s=%1&for /F %%a in ('"prompt $H&echo on&for %%b in (1)do rem"')do set D=%%a
echo %s:^H=!D! !D!%

The first line is a way of saving a few bytes over the lengthy @echo off&setLocal enableDelayedExpansion (which turns echo off and enables the delayed expansion of variables, in case you were wondering). I explained it in Tips for Golfing in Batch.

The second line is a neat little trick to save the a backspace control character into a variable. It's pretty hacky, and I can't pretend to take credit for it. It's sort of explained here. Basically uses the prompt command to generate a backspace character and captures it in a variable - in this case !D!.

The final line then performs the simple string manipulation of - replace ^H with !D!<SPACE>!D!.

C:\>bsp.bat "testing^H^H^H test"
"test test"

Unfortunately it breaks with cases like "AAA^HB^H^H" - where it should produce "A", it instead produces "A"B. Which is somewhat confusing. I'll have to look into how Batch string manipulation works in some more depth.

C:\>bsp.bat "AAA^HB^H^H"

Thanks to to some helpful people over here - I now realize that I was only saving the backspace character (0x08), and so was only overwriting the characters. It now works with examples like the following:

C:\>bsp.bat "AAA^HB^H^H"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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