Pergunta

Given a string "ABCDE", how do i find the index of occurrence of another string "C" in Golfscript?

? operator doesn't seem to work (http://www.golfscript.com/golfscript/builtin.html#?):

"C" "ABCDE" ?

Foi útil?

Solução

"C""ABCDE".,,@`@`{@>1$,<=}++?

There's no way that "C" "ABCDE" ? would work - if that did a string search, it would be looking for the first occurrence of ABCDE in C.

However, in GolfScript strings are really a different presentation of arrays of integers. "ABCDE"67? gives 2 because 67 is the Unicode codepoint for C.

One slightly nicer approach which you might expect to work but doesn't is (X)

"C""ABCDE".,,\`{>1$,<}+%\?

This is rather counter-intuitive, but "correct": ? is an order operation, and string has priority over array. Compare:

[[1][2][3][4][5]][3]?
["1""2""3""4""5"]"3"?

The first gives 2, as expected, but the second gives -1 because the priority of string means that it's searching for the array inside the string - and no array will ever be equal to an int representing a Unicode codepoint. However, these examples do point the way to another approach of reducing the strings to arrays of ints before using approach X.

Update

I sent an e-mail to flagitious suggesting a patch and the latest version of Golfscript has new behaviour for string string ? and string array ?. So if you update, "ABCDE""C"? should give 2.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top