37
\$\begingroup\$

(heavily inspired by Element of string at specified index)

Given a string s and an integer n representing an index in s, output s with the character at the n-th position removed.

0-indexing and 1-indexing are allowed.

  • For 0-indexing, n will be non-negative and less than the length of s.
  • For 1-indexing, n will be positive and less than or equal to the length of s.

s will consist of printable ASCII characters only (\x20-\x7E, or   through ~).

Any reasonable input/output is permitted. Standard loopholes apply.

Testcases (0-indexed):

n s        output
0 "abcde"  "bcde"
1 "abcde"  "acde"
2 "a != b" "a = b"
3 "+-*/"   "+-*"
4 "1234.5" "12345"
3 "314151" "31451"

Testcases (1-indexed):

n s        output
1 "abcde"  "bcde"
2 "abcde"  "acde"
3 "a != b" "a = b"
4 "+-*/"   "+-*"
5 "1234.5" "12345"
4 "314151" "31451"

This is , so shortest answer in bytes wins.

\$\endgroup\$
9
  • 9
    \$\begingroup\$ No one else answer, C# is winning... too late :( \$\endgroup\$ May 19, 2017 at 13:55
  • \$\begingroup\$ Can we assume that the char at that idx appears only once? \$\endgroup\$
    – user58826
    May 19, 2017 at 13:59
  • 1
    \$\begingroup\$ @programmer5000 Last test case 3, 314151 -> 31451. I'd assume not. \$\endgroup\$ May 19, 2017 at 14:01
  • \$\begingroup\$ @programmer5000 No. See the last test case. \$\endgroup\$ May 19, 2017 at 14:01
  • 2
    \$\begingroup\$ Maybe a leaderboard would be helpful, there are plenty of answers to search through already. \$\endgroup\$
    – Mr. Xcoder
    May 20, 2017 at 4:26

78 Answers 78

2
\$\begingroup\$

R, 48 47 bytes

(1 byte saved through use of el() thanks to Giuseppe)

function(s,n)cat(el(strsplit(s,""))[-n],sep="")

Split the string into its individual characters, remove the nth and then concatenate again.

There may well be a better solution, strsplit() is quite unwieldy as it returns a list.

\$\endgroup\$
5
  • \$\begingroup\$ won't work on TIO: pryr::f([function body]) saves a few bytes and using el(strsplit(s,"")) saves a byte but also doesn't work on TIO for some reason. \$\endgroup\$
    – Giuseppe
    May 23, 2017 at 18:25
  • \$\begingroup\$ @Giuseppe Thanks! I would feel a bit dirty making use of pryr::f since surely it should be preceded by install.packages("pryr") but maybe that's me being too precious! \$\endgroup\$ May 24, 2017 at 18:42
  • \$\begingroup\$ function(s,n)intToUtf8(utf8ToInt(s)[-n]) for 40 bytes. \$\endgroup\$
    – J.Doe
    Sep 21, 2018 at 17:23
  • \$\begingroup\$ @J.Doe good spot! That's a very different approach so you should post it as your own answer. \$\endgroup\$ Sep 22, 2018 at 6:30
  • \$\begingroup\$ Another sub-47 is function(s,n)sub(sub(0,n,"(.{0})."),"\\1",s) for 44. \$\endgroup\$
    – J.Doe
    Oct 5, 2018 at 15:46
2
\$\begingroup\$

Cubically, 46 56 34 bytes

R3D1R1$:7~?6{(~@7-0)6}~(~-0=7&6@7)

(0-based index)

Try it online! You must change &6 to ?6& on TIO due to a bug in the interpreter.

How it works

R3D1R1$:7~?6{(~@7-0)6}~(~-0=7&6@7)
R3D1R1                             Set the top face to 1
      $                            Get next numeric input
       :7                          Set notepad to input
         ~                         Read (skip) next character (space)
          ?6{        }             If notepad is nonzero
             (     )6              While notepad is nonzero
              ~@7                  Print next inputted character
                 -0                Subtract 1 from notepad
                      ~            Read (skip) next character
                       (         ) Loop indefinitely
                        ~          Get next character
                         -0=7&6    Exit program if input is -1 (EOF)
                               @7  Output the input
\$\endgroup\$
2
\$\begingroup\$

q, 6 1 byte

_

Test Cases

q)"abcde"_0
"bcde"
q)"abcde"_1
"acde"
q)"a != b"_2
"a = b"
etc.
\$\endgroup\$
2
  • 1
    \$\begingroup\$ why not just _? :) it's ok to swap the arguments, many answers already do that \$\endgroup\$
    – ngn
    Sep 28, 2018 at 1:11
  • \$\begingroup\$ I suppose you're right, it's built in functionality, thanks \$\endgroup\$
    – Thaufeki
    Sep 28, 2018 at 1:33
1
\$\begingroup\$

PowerShell, 25 Bytes

3 Options, all the exact same bytecount.

$a,$b=$args;$a|% *ve $b 1

$args[1]|% *ve $args[0] 1

param($a,$b)$a|% *ve $b 1

calls .Remove on the string, using the number as an arg.

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

JavaScript (ES6), 39 34 33 bytes

n=>s=>s.replace(/./g,c=>n--?c:"")
  • 5 6 bytes saved thanks to Arnauld.
\$\endgroup\$
0
1
\$\begingroup\$

Javascript (ES6), 48 bytes

x=>i=>x.substring(0,i-1)+x.substring(i,x.length)

Or this (55 bytes)

n=[],x=>i=>x.split``.forEach((_,i)=>i==x?0:n.push(_))
\$\endgroup\$
2
  • \$\begingroup\$ Just wanted to say, community downvoted this post because it was flagged as "low quality" (I think) and then I edited it, causing it to downvote. Welcome to the site! \$\endgroup\$
    – user58826
    May 19, 2017 at 16:03
  • \$\begingroup\$ You can save some bytes in the second one by replacing ("") with ``, and (x,i) with x=>i in the first and second one. \$\endgroup\$
    – user58826
    May 19, 2017 at 16:04
1
\$\begingroup\$

C (gcc) - 45 44 bytes

-1 Thanks to @Niel !

f(s,n)char*s;{for(;*s;++s)n--&&putchar(*s);}

alternative, 45 bytes :

g(s,n)char*s;{s[n++]=0;printf("%s%s",s,s+n);}

try it online

\$\endgroup\$
0
1
\$\begingroup\$

Chip, 115 bytes

*Z~S
,x.z.
`@z\{Aa
,x.|*
`@z\{Bb
,x.|
`@z\{Cc
,x.|*
`@z\{Dd
,x.|
`@z\{Ee
,x.|*
`@z\{Ff
,x.|
`@z\{Gg
,x.|*
`@z\{H
 S

The first byte of input is a 0-based index, the remainder is the string to process: \x02abcde.

Try it online!
In this TIO, a newline character is the index, which means an index of 0x0a = 10.

Test cases!
These use hex input + printf to make it clearer what's happening.

How does it work?

*Z~S

This suppresses output on the first byte, because we don't want to print the index. That'd be silly.

Aa, Bb, Cc, etc.

These relay the input to the output for every byte, unless suppressed. Note that the h is missing, this is because we never need to output something with the high bit set.

,x.
`@z\{D

This is the real meat of it all. There are eight of these, one for each bit of the index (a one-byte index means that indexes are not able to be specified above 255). This reads in the index on the first cycle only with switches (\). The index bits have been flipped with an xor gate ({), which is almost negation. Then, for each character of the string, this value is incremented via some half-adders (@). When this value is incremented from 0xff to 0x00, it uses the carry from the high bit to suppress output (S) for that character, effectively removing it from the string.

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

J, 8 bytes

{.,1}.}.

Uses zero-based indexing.

Try it online!

Explanation

{.,1}.}.  Input: integer n (LHS), string s (RHS)
      }.  Drop the first n chars of s
   1}.    Drop one char from that
{.        Take the first n chars of s
  ,       Join them
\$\endgroup\$
1
\$\begingroup\$

(s)ed - 6 bytes

1-based indexing.

s/.//n

Explanation:

s       # substitute command.
 /./    # match any single char.
   //   # substitution is empty.     
     n  # Only match the 'n'th occurrence in a line. 
\$\endgroup\$
3
  • 4
    \$\begingroup\$ Unfortunately, hardcoding part of the input into the program is not allowed. You'd have to get n from the user (STDIN, command-line arguments, etc.), which I'm not sure is possible in sed. There's always the option to wrap your solution in a Bash script though. \$\endgroup\$
    – Dennis
    May 20, 2017 at 14:23
  • 1
    \$\begingroup\$ If you do sed s/.//$1 and call it a BASH + GNU utilities answer, I think it will be a good 11-byte answer and I'll change my downvote to an upvote :) \$\endgroup\$ May 20, 2017 at 16:39
  • \$\begingroup\$ Yes the fun of being a newbie I'll re-read the linked thread and try to do it all within sed. I assumed that because all of the typed languages were sparse that it was preferred. I know I can resort to ssed if it is going to be "GNU utilities" without a shell, not that I am anti GNU but the 'n' flag is a 4.4BSD feature IIRC. \$\endgroup\$
    – gdahlm
    May 20, 2017 at 22:35
1
\$\begingroup\$

R, 45 bytes

pryr::f(sub(paste0("(.{",n-1,"})."),"\\1",s))
\$\endgroup\$
1
  • \$\begingroup\$ couldn't you just use n instead of n-1 and say it's 0-indexed? Also, just for fun you could use sprintf('(.{%d}).',n-1) instead of the paste0 expression and it would have the same length as your current answer. \$\endgroup\$
    – Giuseppe
    May 23, 2017 at 18:33
1
\$\begingroup\$

SmileBASIC 3, 23 bytes

We have character indexing, why not use it? Set a character index to the empty string to delete it.

Defines a command A which prints the output. Uses 0-indexing.

DEF A S,N
S[N]="
?S
END
\$\endgroup\$
1
\$\begingroup\$

C, 57 50 bytes

#define f(s,n)for(i=n;s[i];i++)s[i]=s[i+1];puts(s)

0-indexed, naturally. I call this macro with:

int main(int argc, char **argv)
{
    if (argc != 3)
        return;
    f(argv[1],atoi(argv[2]));
}
\$\endgroup\$
2
  • \$\begingroup\$ Could you shorten i<strlen(s); to s[i]? (I see you have done this in your shortC answer) Clever algorithm, btw. \$\endgroup\$ May 20, 2017 at 19:23
  • \$\begingroup\$ @ETHproductions Oops, meant to put that in here. Thanks \$\endgroup\$
    – MD XF
    May 20, 2017 at 20:33
1
\$\begingroup\$

Excel, 29 bytes

=LEFT(A1,A2)&MID(A1,A2+2,9^9)

Assumes input in cells A1 (string) and A2 (integer, 0-indexing).

Takes the left part of the string with LEFT and the right part - actually a substring starting on position A2+2 and 9^9 characters long (which is more then the max string length in one cell: 32,767 characters).

\$\endgroup\$
2
  • \$\begingroup\$ I think that you have miscounted your byte count. I see 29 bytes :) \$\endgroup\$ May 22, 2017 at 14:40
  • 1
    \$\begingroup\$ @Taylor thanks, I must have had a trailing space when pasting into byte count tool. \$\endgroup\$
    – pajonk
    May 22, 2017 at 15:19
1
\$\begingroup\$

Bash, 83 24 22 bytes

echo ${1::$2-1}${1:$2}

24 bytes answer given by Digital Trauma

-2 bytes, quotation marks not needed

My first GodeGolf answer, any feedback is apreciated

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Welcome to PPCG! \$\endgroup\$ May 19, 2017 at 21:14
  • \$\begingroup\$ How about echo "${1::$2-1}${1:$2}"? \$\endgroup\$ May 20, 2017 at 6:01
  • \$\begingroup\$ @DigitalTrauma welp, i tried that and thought it didnt work because i was testing with 0 indexed \$\endgroup\$
    – DrnglVrgs
    May 23, 2017 at 14:51
1
\$\begingroup\$

Rebol, Red - 12 bytes

 remove at s n
\$\endgroup\$
2
  • 2
    \$\begingroup\$ Hello and welcome to PPCG. I am unfamiliar with Rebol -- does your code reflect a full program or any function-esk construct? Snippets do not count as valid submissions to standard code golf challenges. \$\endgroup\$ Sep 21, 2018 at 1:23
  • \$\begingroup\$ This does not appear to be valid - we require solutions to be either full programs or functions, unless stated otherwise. We don't allow the assumption that input is already in predefined variables. In order for this to be a valid function submission, it would need to be func [s n] [remove at s n] (assuming I'm reading the documentation correctly). \$\endgroup\$
    – user45941
    Sep 21, 2018 at 2:22
1
\$\begingroup\$

Lua, 51 38 bytes

Lowered to 38 bytes thanks to Jo King

x,y=...print(y:sub(1,x-1)..y:sub(x+1))

Try it online!

Just like everything else in Lua this is 1-indexed.

Explanation

Lua uses a table called arg to store arguments and the function sub() returns a substring of the string passed.

This is my first code golf entry, please be nice :)

\$\endgroup\$
2
  • \$\begingroup\$ You wrote wlse -- did you mean wise? \$\endgroup\$ Sep 20, 2018 at 21:09
  • \$\begingroup\$ Welcome to PPCG! You can use ... to get this down to 38 bytes! \$\endgroup\$
    – Jo King
    Sep 21, 2018 at 0:35
1
\$\begingroup\$

Attache, 13 bytes

{_[0:#_^^_2]}

Try it online!

Explanation

{_[0:#_^^_2]}
{           }    anonymous lambda (_ = 1st argument, _2 = 2nd argument)
   0:#_          range from 0 to the length of _
       ^^_2      ...without the 2nd argument
 _[        ]     obtain characters from _ using that range
\$\endgroup\$
1
\$\begingroup\$

Runic, 48 bytes

   /~~{ R:1(?\~@
/3{\?)0:\S{-1/
\s3s}}1-U}:irui<

Try it online!

Not all test cases work at the moment: a few (more) flaws discovered in the parser.

  • Numbers are read as numerical values and don't unconcatenate (I need to call .ToString() on the popped object, then split the result into a char array; this will match intended spec of "doing operations to the best of the execution context's ability with the given stack values)
  • Spaces (and other white space) are input value separators (I need to readd the control character demarcation; got lost in the previous attempts to fix the next issue). After fixing inputs such as a != b would need to be passed as a\ !=\ b
  • Input needs a trailing newline (have not discovered a fix to this yet)

Other test cases work (and are considered 0-indexed).

Explanation

Flow

Program starts in the lower right (red), reads a string, unconcatenates it, reverse it (so the first character is at the top of the stack; behavior is so that u followed by q results in concatenation in the desired order, and q works the way it does because >'a'bq, >`ab`q, and >"ab" should all have the same result). Then the program reads the integer value and assumes (per question spec) that it is in the range [0,L), values above this range will simply loop (effective %). This value is duplicated and stored at the bottom of the stack for later.

The lower left portion (yellow) is the section responsible for shifting the string around on the stack N times, where N is the input value. The 3s3s portion rotates the top 2 items on the stack below the 3rd (which results in the front-most character in the string being rotated to the end without affecting the positions of the two counters with the next two } rotates). It exits this branch along the top (green), heading right and popping 2 values (the loop counter and then the character to discard) and rotating the saved input value back to the top.

The top right (blue) then loops the remaining characters back into place in reverse, exiting the loop (purple) towards the @ which discards the remaining loop counter and prints the stack top to bottom.

Picture has a mistake, along the bottom are some stack manipulators, }}}{ and in typing up this post I noticed that }{ cancels out and saves 3 bytes.

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

Factor, 10 bytes

remove-nth

Try it online!

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

Befunge-93, 26 bytes

&>1# -#,:#~_~~>:# 1#~+#,_@

Try it online!

1-indexed, does NOT require a null byte at the end of the string because that's lame. However, if you really want to get all "let's screw with the input format to make the code shorter", here is one that saves 3 bytes by assuming a null terminator:

&>1# -#,:#~_~~>:#~ #,_@
\$\endgroup\$
0
\$\begingroup\$

Perl 5, 19 bytes

18 bytes of code + -p flag

substr($_,<>,1)=""

Try it online!

substr($_,<>,1) returns 1 character at index <> (the 2nd input) in the string $_ (the input). And ="" changes it to "". And $_ is implicitely printed at the end thanks to -p flag.

\$\endgroup\$
0
\$\begingroup\$

Go, 50 bytes

1-indexed because we're all human, I think.

func f(s string,n int)string{return s[:n-1]+s[n:]}

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ Also note that the import statement is not being included because it is not being used in the function but rather for testing of it. Go requires an import to print stuff out. \$\endgroup\$ May 19, 2017 at 15:34
0
\$\begingroup\$

Lua, 37 bytes

Uses 0 indexing

s,i=...
print(s:sub(1,i)..s:sub(i+2))

Try it online!

\$\endgroup\$
0
\$\begingroup\$

QBIC, 28 bytes

B=@ `+B?_t_s;,:|+_sB,a+2,_lB

This is an adaptation of my Substring Subtraction answer.

Explanation:

B=@ `+B     Prepend a space to the input string
?           PRINT
 _t           a trimmed version (drops the space again)
   _s         SUBSTRING
     ;,:|       Read B$ from cmd line, read n from cmd line
                SUBSTRING with a stirng and a positive N takes chars 1-N from the left.
   +_sB       Plus a second substring
     ,a+2       Starting behind the removee-index
     ,_lB       taking all the remaining characters

This could go all the way down to 22 bytes if I didn't need that hacky space prepended. Time to change Substring-behaviour for this use-case...

?_s;,:-1|+_sA,a+1,_lA
\$\endgroup\$
0
\$\begingroup\$

Braingolf, 38 37 bytes

VVR<lMMv.M2+-[R<vv]R$_v.?1-[R<v]|R&@;

Try it online!

0-based index

As always with Braingolf, the TIO link includes the entire Python3 parser. The code is the 2nd argument, the index is the 3rd argument, and the string is the 4th argument.

\$\endgroup\$
0
\$\begingroup\$

Retina, 29 bytes

1`\d+
$*	
+`(	+)	(.)
$2$1
	.

Try it online!

The index and the string are on the same line separated by one tab. The index is zero-based.

\$\endgroup\$
0
\$\begingroup\$

Brain-Flak, 39 bytes

{({}<({}<>)<>>[()])}{}{}<>{({}<>)<>}<>

Try it online!

This has a one byte penalty for the -c flag which enables ASCII input and output. This takes the first parameter as a character code, which OP has allowed.

So the input is

0x01abcde

This uses zero indexing. Unfortunately, TIO doesn't allow null bytes in input, but this works locally so it's not an issue.

\$\endgroup\$
0
\$\begingroup\$

Swift - 86 bytes (0-indexed)

func l(s:String,n:Int){var a=s;a.remove(at:a.index(a.startIndex,offsetBy:n));print(a)}

Function that can be used as l(s:"abcdefg",n:3)

Check it out!


Swift - 120 bytes

Since I thought the above is quite boring, I came up with another solution:

func l(s:String,n:Int){let b=s.startIndex;print(s[b...s.index(b,offsetBy:n-1)]+s[s.index(b,offsetBy:n+1)..<s.endIndex])}

Works as the one below, it's just more interesting.

\$\endgroup\$
0
\$\begingroup\$

shortC, 36 bytes

Df(s,n)Oi=n;s[i];i++)s[i]=s[i+1];Js)

See my plain C answer for how to call the macro.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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