Usuń znak pod określonym indeksem


(silnie zainspirowany Elementem ciągu o określonym indeksie )

Biorąc pod uwagę ciąg si liczbę całkowitą nreprezentującą indeks w s, wyprowadzaj sznak ze znakun -tej pozycji usuniętej.

Dozwolone jest indeksowanie 0 i indeksowanie 1.

  • W przypadku indeksowania 0 wartość nbędzie nieujemna i mniejsza niż długość s.
  • Dla 1-indeksowania nbędzie dodatnia i mniejsza lub równa długości s.

sbędzie się składać wyłącznie z drukowalnych znaków ASCII ( \x20-\x7Elub  przez ~).

Wszelkie uzasadnione wejścia / wyjścia są dozwolone. Obowiązują standardowe luki .

Przypadki testowe (indeksowane 0):

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

Testcases (1-indeksowany):

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

To jest , więc wygrywa najkrótsza odpowiedź w bajtach.

Nikt inny nie odpowiada, C # wygrywa ... za późno :(

Czy możemy założyć, że znak na tym idxie pojawia się tylko raz?

@ programmer5000 Ostatni przypadek testowy 3, 314151-> 31451. Zakładam, że nie.

@ programmer5000 Nie. Zobacz ostatni przypadek testowy.

Może przydałaby się tabela liderów, istnieje wiele odpowiedzi do przeszukania.
Pan Xcoder,



Alice, 13 12 bytes

Thanks to Leo for saving 1 byte.

@ q

Try it online!

First line of the input is the string, second line is the 0-based index.


/    Reflect to SE. Switch to Ordinal. While in Ordinal mode, the IP bounces
     diagonally up and down through the code.
I    Read the first line of input (the string).
!    Store the string on the tape, which writes the characters' code points to 
     consecutive cells (the tape is initialised to all -1s).
]    Move the tape head right. This moves it by an entire string, i.e. to the
     cell after the -1 that terminates the current string.
     The IP bounces off the bottom right corner and turns around.
]    Move the tape head right by another cell.
!    Store an implicit empty string on the tape, does nothing. It's actually
     important that we moved the tape head before this, because otherwise it
     would override the first input code point with a -1.
I    Read the second line of input (the index) as a string.
/    Reflect to W. Switch to Cardinal.
     The IP wraps around to the last column.
&]   Implicitly convert the first input to the integer value it contains
     (the index) and move the tape head that many cells to the right, i.e.
     onto the character we want to delete. Note that Ordinal and Cardinal mode
     have two independent tape heads on the same tape, so the Cardinal tape
     head is still on the first cell of the string input before we do this.
e!   Store a -1 in the cell we want to delete.
\    Reflect to SW. Switch to Ordinal.
q    Push the entire tape contents as a single string. This basically takes
     all cells which hold valid code points from left to right on the tape 
     and concatenates the corresponding characters into a single string. Since
     we wrote a -1 (which is not a valid code point) over the target character,
     this will simply push the entire input string without that character.
o    Output the result.
@    Terminate the program.


Haskell, 28 24 Bytes

-4 byte thanks to Laikoni, this version is 1-indexed.

s#n=take(n-1)s++drop n s

Old answer:

f(s:t)0=t;f(s:t)n=s:f t(n-1)

A simple recursive function that takes the value, it's 0-indexed.

My first time code-golfing so maybe it's not the optimal solution. Oh well.

Welcome to PPCG!
Martin Ender

Also you might be interested in the collection of tips for golfing in Haskell.


Mathematica, 18 bytes




[1, "abcde"]

thanks Martin Ender

In my opinion, "Any reasonable input/output is permitted" allows for the input to be taken like ["abcde", {1}], in which case StringDrop alone does the trick. What do you think? (You might want to explicitly mention that it's 1-indexed as well.) I'm always happy to see people posting Mathematica answers :)
Greg Martin


CJam, 4 bytes


Try it online!


q~    e# Read and eval input (push the string and number to the stack).
  Lt  e# Set the nth element of the string to the empty string.


GCC c function, 25

1-based indexing.


Plenty of undefined behavior here so watch out for stray velociraptors:

  • The strcpy() man page says If copying takes place between objects that overlap, the behavior is undefined. Here there clearly is overlap of the src and dest strings, but it seems to work, so either glibc is more careful or I got lucky.
  • The answer is reliant on the fact that the s+=n happens before the s-1. The standard gives no such guarantees, and in fact calls this out as undefined behaviour. Again, it seems to work as required with the gcc compiler on x86_64 Linux.

Try it online.

In a stack-based ABI, such as x86, strcpy's arguments need to be pushed in right-to-left order, which would explain the behaviour, but you said you were using x86_64 which uses registers... maybe the compiler decided to golf the generated code and decided that computing s+=n first was golfier!

I love it when C answers go "this has no official reason to work, but it does anyway, so... eh."

Holy crap. This blows mine out of the water. Very impressive!

@Quentin That's one of the fun things about code-golf - you are allowed - encouraged even - to write the most awful, unsafe code that would normally be a firing offence ;-)
Digital Trauma

I'd love to know the reason for the downvote...
Digital Trauma


MATL, 3 bytes


Uses 1-based indexing.

Try it online! Or verify all test cases.


&    % Specify secondary default number of inputs/outputs for next function
)    % Implicitly input string and number. Index: with & it pushes the char
     % defined by the index and the rest of the string
&    % Specify secondary default number of inputs/outputs for next function
     % Implicitly display (XD): with & it only displays the top of the stack

In the modified version with all the test cases, the code is within an infinite loop `...T until no input is found. At the end of each iteration the display function (XD) is explicitly called, and the stack is cleared (x) to ready it for the next iteration.

I like the idea of generic command modifiers, they might be useful in other golfing languages.

@ETHproductions If you need a name, I call them meta-functions, as they modify functions
Luis Mendo

@LuisMendo I think the formal name would be operators, a la mathematical operators (aka higher-order functions).


Vim, 7 bytes


How it works:

It expects two lines; one with the string and one with the number.

  1. Go to line two, copy the number into register
  2. Go to first line and then go to column in the register with @"|
  3. Delete the character under the cursor

Another fun solution that's almost identical is jD@"gox

Flagging -> Closing -> Duplicate of :P kidding, but they are remarkably similar.

they are! Is there any prize for getting down to 7 characters first? :-P


Java 8, 39 bytes


Try it here.

Java 7, 67 bytes

String c(int n,String s){return s.substring(0,n)+s.substring(n+1);}

Try it here.

Assuming it works, a "built in" for 46 bytes s->n->new StringBuilder(s).deleteCharAt(n)+""; though it is longer.

@TheLethalCoder It indeed works. But it's indeed a bit longer. Oh, and always use StringBuffer instead of StringBuilder in codegolf. ;)
Kevin Cruijssen

Ah nice trick on the buffer I used it in my answer :)


Haskell, 15 bytes

This requires the recently released GHC 8.4.1 (or higher). Now <>, as a function on Semigroups, is in Prelude. It is particularly useful on the function Semigroup


Try it online!
Since tio is using an older bersion of GHC, I've imported <> in the header.


R, 40 bytes

Just goes to show the variety of ways, none of which particularly compact, you can fiddle with strings in R.



05AB1E, 5 bytes


Try it online!

ā     # push range(1, len(input string) + 1)
 ²Ê   # Check each for != to input index
   Ï  # Keep characters from input where this array is 1
    J # Join


JS (ES6), 41 32 31 bytes


Based on this. Takes input through currying, first is string, second is index.

-9 thanks to @JohanKarlsson

-1 thanks to @ETHproductions


Jelly, 3 bytes


A full program taking the (1-based) index and the string (in that order) and printing the result.

As a dyadic function it returns a list of the two parts.

In fact the index may be a list of n indices, in which case it returns a list of the n-1 parts.

Try it online!, or see a test suite.


Ṭœp - Main link: number i, string s                   e.g. "fish 'n chips", 6
Ṭ   - untruth - get a list with 1s at the indexes of i      000001 <-- i.e. [0,0,0,0,0,1]
 œp - partition s at truthy indexes without borders       ["fish ","n chips"]
    - implicit print                                        fish n chips

As an example of using multiple indexes:

      "fish and chips", [6,8]
Ṭ      00000101 <- i.e. [0,0,0,0,0,1,0,1]
 œp  ["fish ","n"," chips"] 
       fish n chips


vim, 10 7


Takes 1-indexed input in the following format:

D      delete the number on the first line into register "
gJ     remove the newline while preserving whitespace on line 2
@"     run the " register as a macro - input is used as a count for...
|      the "go to nth column" command
x      delete the character at the cursor

Thanks to @DJMcMayhem for 3 bytes!


Java 8, 45 41 bytes

s->n->new StringBuffer(s).deleteCharAt(n)

Saved 4 bytes thanks to @OlivierGrégoire

My first code golf answer in something other than C#, even if it isn't the shortest for Java yet.

1. You don't need the final ; in lambda (-1 bytes). 2. In my eyes, you don't need to return a String. I think that returning the StringBuffer without the +""would be perfectly valid (-3 bytes). Example? BigInteger is a representation of an unbounded int, in this case StringBuffer/StringBuilder are representations of mutable Strings.
Olivier Grégoire

@OlivierGrégoire Thanks :) I've never actually used Java before so all improvements are welcome


JavaScript (ES6), 39 34 33 bytes

  • 5 6 bytes saved thanks to Arnauld.


PHP, 41 bytes, 35 bytes excluding ?php

<?php $argv[1][$argv[2]]='';echo$argv[1];



I'm actually really surprised this works; is the [$argv[2]] index implicitly creating a range? Also, IIRC you can leave the <?php off, because the PHP interpreter has a mode which doesn't need it, and because we don't normally penalise for that sort of indication in a file of what the language is.

@ais523 Basically yes. From docs: "Characters within strings may be accessed and modified by specifying the zero-based offset of the desired character after the string using square array brackets, as in $str[42]. Think of a string as an array of characters for this purpose."


R, 48 47 bytes

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


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.

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.

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

function(s,n)intToUtf8(utf8ToInt(s)[-n]) for 40 bytes.

@J.Doe good spot! That's a very different approach so you should post it as your own answer.

Another sub-47 is function(s,n)sub(sub(0,n,"(.{0})."),"\\1",s) for 44.
Korzystając z naszej strony potwierdzasz, że przeczytałeś(-aś) i rozumiesz nasze zasady używania plików cookie i zasady ochrony prywatności.
Licensed under cc by-sa 3.0 with attribution required.