Given a string s
and a non-negative number n
less than the length of s
, output the character at the n
-th position of s
.
0-indexing and 1-indexing are allowed. For 1-indexing, n
will be positive and less than or equal to the length of s
.
s
will consist of printable characters only.
Any reasonable input/output is permitted. Standard loopholes apply.
Testcases (0-indexing):
n s output
0 "abcde" a
1 "abcde" b
2 "a != b" !
3 "+-*/" /
4 "314159" 5
Testcases (1-indexing):
n s output
1 "abcde" a
2 "abcde" b
3 "a != b" !
4 "+-*/" /
5 "314159" 5
This is code-golf, so shortest answer in bytes wins.
-
16\$\begingroup\$ I downvoted this because it's not really a programming or golfing challenge; all that's essentially being asked here is which language has the shortest built-in for the job. \$\endgroup\$Shaggy– Shaggy2017年05月13日 14:11:12 +00:00Commented May 13, 2017 at 14:11
-
18\$\begingroup\$ @Shaggy Same for many other simple challenges like adding two numbers, testing if a number is prime or printing "Hello, World!". While these are boring in many languages that can do them out of the box, they can be interesting challenges for more primitive languages that have to roll their own implementation. Plus, anything more complicated is usually too much to ask of those languages, so it's nice to have an outlet for them. If trivial challenges bore you, try doing them in a nontrivial language. \$\endgroup\$Martin Ender– Martin Ender2017年05月13日 14:15:23 +00:00Commented May 13, 2017 at 14:15
80 Answers 80
MATL, 1 byte
)
Well, hard to make it much simpler. )
indexes the first input, using the second input value. This is 1-indexed.
Alice, 5 bytes
I&IO@
As usual it's much shorter if we avoid Ordinal mode and use an abysmal input format. Here, the first character's code point is used as the integer input. The remainder of the input is the string. The index is 1-based.
Explanation
I Read a character and push its code point.
&I Read that many more characters and push them.
O Output the last one we read.
@ Terminate the program.
-
\$\begingroup\$
abysmal
- I thought you made it xD \$\endgroup\$Stephen– Stephen2017年05月13日 12:29:18 +00:00Commented May 13, 2017 at 12:29 -
\$\begingroup\$ @StephenS You mean I proposed this I/O format on meta? Yeah, I did, but mostly for languages that would have to implement their own decimal integer parser/renderer each time they compete in a challenge with numerical I/O, so they would likely just skip those entirely. But it has the unfortunate side effect that in some languages which can read and write decimal quite easily it's still shorter to use code points instead. \$\endgroup\$Martin Ender– Martin Ender2017年05月13日 13:58:45 +00:00Commented May 13, 2017 at 13:58
Python, 15 bytes
str.__getitem__
or
lambda s,i:s[i]
Both take 2 arguments: the string and the index. 0-indexed.
-
\$\begingroup\$ I'm surprised both methods have the same length. \$\endgroup\$Leaky Nun– Leaky Nun2017年05月13日 10:48:26 +00:00Commented May 13, 2017 at 10:48
Haskell, 4 bytes
(!!)
0-based indexing. Usage example: (!!) "Hello" 1
-> 'e'
.
Octave, 10 bytes
@(s,n)s(n)
Takes a string s
, and a number n
as input, and returns the n
th character of s
.
Retina, (削除) 28 (削除ここまで) (削除) 20 (削除ここまで) 19 bytes
Saved 8 bytes thanks to @MartinEnder by not using balancing groups
Saved 1 byte thanks to @mbomb007 by using ^.+
instead of ^\d+
^.+
$*
+`1¶.
¶
!1`.
The program is 0-indexed.
Alice, 10 bytes
/@!O?]&
I
Expects the string on the first line and the 0-based index on the second line.
Explanation
Despite its wealth of built-ins, string indexing doesn't exist in Alice. The reason is that it requires both an integer and a string parameter, and all commands in Alice are strictly integers to integers or strings to strings.
In general, the main way to perform any operations on strings that require or result in integers is to store the string on the tape in Ordinal mode, which you can then manipulate with integers in Cardinal mode.
/ Reflect to SE. Switch to Ordinal. While in Ordinal mode, the IP bounces
diagonally up and down through the program.
I Read one line from STDIN and push it.
! Store the string on the tape. This writes the character codes into consecutive
tape cells starting at the tape head. (It also writes a -1 at the end as a
terminator, but the tape is initialised to -1s anyway).
The next few commands are junk that luckily doesn't affect the program:
? Load the string from the tape and push it to the stack again.
& Fold the next command over this string. That is, for each character
in the string, push that character, then execute the command.
? So we're folding "load" over the string itself. So if the string is "abc"
we'll end up with "a" "abc" "b" "abc" "c" "abc" on the stack.
! Store the top copy of "abc" on the tape (does nothing, because it's
already there).
Now the relevant part of the program continues.
I Read another line from STDIN, i.e. the string representation of the index.
/ Reflect to W. Switch to Cardinal. The IP wraps to the last column.
& Implicitly convert the string to the integer value it represents and
repeat the next command that many times.
] Move the tape head right that many cells. Note that Ordinal and Cardinal
mode have separate tape heads, but they are initialised to the same cell.
? Load the value from that cell, which is the code point of the character
at the given index.
O Print the corresponding character.
! This discards or converts some of the strings on the stack and writes some
value back to the tape, but it's irrelevant.
@ Terminate the program.
-
1\$\begingroup\$ "Despite its wealth of built-ins, string indexing doesn't exist in Alice." >_> \$\endgroup\$Leaky Nun– Leaky Nun2017年05月13日 10:49:04 +00:00Commented May 13, 2017 at 10:49
-
1\$\begingroup\$ @LeakyNun If you think that's bad, there's also no built-in to get a string's length. ;) \$\endgroup\$Martin Ender– Martin Ender2017年05月13日 10:52:34 +00:00Commented May 13, 2017 at 10:52
JavaScript, (削除) 11 (削除ここまで) 10 bytes
s=>n=>s[n]
Uses 0-based indexing.
-1 byte thanks to @Leaky Nun
f=
s=>n=>s[n]
console.log(f("abcde")(0));
console.log(f("abcde")(1));
console.log(f("a != b")(2));
console.log(f("+-*/")(3));
console.log(f("314159")(4));
-
1\$\begingroup\$ you can use currying
s=>i=>s[i]
to save a byte \$\endgroup\$Leaky Nun– Leaky Nun2017年05月13日 10:40:21 +00:00Commented May 13, 2017 at 10:40 -
1\$\begingroup\$ Every time I see answers like this it annoys me because I know the C# version is always one byte longer for the semi colon on the end. And that is indeed the case here \$\endgroup\$TheLethalCoder– TheLethalCoder2017年05月14日 08:37:24 +00:00Commented May 14, 2017 at 8:37
Brachylog, 2 bytes
∋)
Explanation
∋
unifies its output with an element of the Input. With )
as subscript, it will unify its output with the I
th element of S
, with [S,I]
as input.
Cubix, 8 bytes
t@poIA//
This solution is 1-indexed. The input should consist of a number first, then a separator (that is not a digit or a .
) and then the string.
-
\$\begingroup\$ SILOS is back \o/ \$\endgroup\$Leaky Nun– Leaky Nun2017年05月13日 11:42:08 +00:00Commented May 13, 2017 at 11:42
-
1\$\begingroup\$ Yeah, I'm trying to answer as many callenges as possible, including the windows loading screen one. I like the point it's at in terms of graphical output, and libraries, but I still would like to develope a compression scheme to try and get it competitive. Essentially the int[] it compiles to can be generated through reading a byte stream. @LeakyNun \$\endgroup\$Rohan Jhunjhunwala– Rohan Jhunjhunwala2017年05月13日 11:43:46 +00:00Commented May 13, 2017 at 11:43
BF, 9 bytes
,[->,<]>.
The index is taken via the character code of a char (like the Alice submission). Following that, we have the string.
The TIO link uses a Bash wrapper and the input can be changed in the header file (the reason for the wrapper is so that we can see the bytes).
-
\$\begingroup\$ Legit TIO hacking :p \$\endgroup\$Leaky Nun– Leaky Nun2017年05月13日 13:06:55 +00:00Commented May 13, 2017 at 13:06
-
\$\begingroup\$ @LeakyNun I used the wrapper for BF. \$\endgroup\$user41805– user418052017年05月13日 13:08:05 +00:00Commented May 13, 2017 at 13:08
-
1\$\begingroup\$ I did say it is legit. \$\endgroup\$Leaky Nun– Leaky Nun2017年05月13日 13:08:36 +00:00Commented May 13, 2017 at 13:08
-
\$\begingroup\$ Is there a way to do input to other TIO languages like that? Like SMBF? \$\endgroup\$mbomb007– mbomb0072017年05月19日 21:25:38 +00:00Commented May 19, 2017 at 21:25
-
><>, 13 + 1 = 14 bytes
+1 for -v
flag to take input
:?!\i~1-
io;\
Thanks to @steenbergh for notifying me about the -v
flag and saving me 3 bytes!
Input the index with the command line argument -v [index]
(0-indexed) and input the string through stdin.
Explanation
The stack starts with the index on top.
:
duplicates it.
?
ignores the next character if the index is 0. (Popping it off the stack)
If it is zero, \
reflects the direction to go down. Then, it is reflected to the right with the next \
. It wraps around and executes i
nput a character, o
utput it and ;
halts execution.
If not, !
skips the next instruction, so it doesn't go down.
i~
inputs a character and then immediately discards it.
1
pushes 1.
-
subtractes 1
from the index, so one character in the input is consumed and the index is decremented. The program loops around back to the :
.
-
1\$\begingroup\$ There is the
-v <x>
command line parameter, which initialises the stack to hold<x>
on program start. Try it online \$\endgroup\$steenbergh– steenbergh2017年05月13日 15:19:15 +00:00Commented May 13, 2017 at 15:19
Carrot, 16 bytes
$^//.{#}/S1//.$/
The input format is as such:
string
index
And the program is 1-indexed.
Explanation
Carrot has several global variables, one for each type: string, float and array (others to be implemented soon). The program starts in string-mode, where all the operators will affect the global string variable. And I call these variables the "stack".
(Example input: abcdef\n3
)
$ Get the first line of the input and set the stack-string to this value
^ Exit caret-mode
stack-string = "abcdef"
/ Operator (behaves differently depending on the argument)
/.{#}/ And the argument to this operator is a regex, so this program gets the matches of this regex into the stack-array
. Any character
{#} Pops a line from the input. So now this evaluates to # of any character where # is the second line of the input (in this case, 3)
stack-array = ["abc"]
And now we just need to get the last character in this string, but first
S1 Join the array on the number 1 and set this to the stack-string. Because the array only contains one element, the number 1 does not appear in the stack-string.
stack-string = "abc"
/ Operator; because the argument is a regex, this retrieves the matches of the regex:
/.$/ Get the last character in the string
stack-array = ["c"]
Now this returns a one element array containing a string of length one, but it is shown as a string in the website.
If we really wanted to give the result as a string, we could easily do S","
at the end, but it doesn't matter because the output still looks the same on the interpreter.
Batch, 32 bytes
@set/ps=
@call echo(%%s:~%1,1%%
Reads s
from STDIN and takes n
as a command-line parameter.
-
\$\begingroup\$ There's no need for the
[
. \$\endgroup\$Martin Ender– Martin Ender2017年05月13日 10:58:08 +00:00Commented May 13, 2017 at 10:58 -
\$\begingroup\$ But in general if you want characters from strings, you just split the string first instead of converting the code point back:
~1/=
\$\endgroup\$Martin Ender– Martin Ender2017年05月13日 10:58:32 +00:00Commented May 13, 2017 at 10:58 -
\$\begingroup\$ @MartinEnder And that's how you beat Alice up... \$\endgroup\$Erik the Outgolfer– Erik the Outgolfer2017年05月13日 10:59:33 +00:00Commented May 13, 2017 at 10:59
Turtlèd, 9 bytes
!?:[*l+].
explanation:
First off, Turtlèd is grid based, with a turtle thing. There are grid cells the turtle can move left, up, down, and right on, and can write things on the grid cells.
[the first grid cell the turtle starts on is marked with a *]
! input the string into the string variable
? input the number into the number variable
: this command takes the number variable and moves right that many.
hence this moves right by the amount inputted
[* ] this is an `until` loop. the * there means that `until` the turtle ends the loop
on a grid cell with * written on it (that is, the first cell), it will execute
the code inside again and again
l+ the code inside the while loop. the `l` moves the turtle left, and the +
increments the string pointer. the string pointer is used with the string var;
when you want to write something from the string, you use `.`, which writes
the pointed char. the pointed char is the n-th character of the string, n being
the value of the string pointer. this code will execute until the l moves
the turtle back on to the origin cell. since we moved right by the number
inputted, this will increase the string pointer (which starts at 1)
by the amount inputted.
. write the pointed char, which was dealt with in the previous comment.
if 0 is inputted, turtle stayed on the origin square, and executed none
of the loop, and turtle writes the first char of string input.
if 1 is inputted, turtle moved one right, moved one left and incremented
string pointer once, which means the second char is written. and so on.
[the char of input has been written over the origin square]
[implicitly the grid is outputted, which has spaces and blank lines taken out]
[this is the requested char outputted, plus an unavoidable trailing newline
due to how I made the interpreter. sue me]
Clojure, 3
nth
:P What can you do when there is a built-in for this? This works on lists, vectors, strings and sequences. It is either O(1) or O(n), depending on the used datatype.
sed, 31 bytes
:
/^1/{s:1 .: :;b}
s: (.).*:1円:
Input: index and the string, separated by one space. Index in unary, but zero-based.
Dyvil, 4 Bytes
_[_]
Creates an anonymous function that takes a String
and an int
and returns a char
.
Usage:
let f: (String, int) -> char = _[_]
print f("abc", 1) // b
-
\$\begingroup\$ @
Clashsoft
- so the anonymous function binds both input parameters to the same placeholder variable_
???? \$\endgroup\$RARE Kpop Manifesto– RARE Kpop Manifesto2024年06月17日 11:45:18 +00:00Commented Jun 17, 2024 at 11:45
QBasic 4.5, 24 bytes
INPUT a,ドルb:?MID$(a,ドルb,1)
Pretty straightforward.
Mathematica, 18 bytes
#~StringTake~{#2}&
Basic solution, but unfortunately the function name is quite long.