Search code examples
pine-scriptpine-script-v5

Issue retrieving character from a string variable in Pine Script


I'm trying to retrieve the second character from a string variable:

string myString = "Hello"
string secondChar = myString[1]

However, instead of getting "e," the result is "Hello." What am I doing wrong?


Solution

  • [] in pinescript is called history-referencing operator. It is used to access historical values of a variable.

    You can convert your string to an array with the str.split() function and then access the chars with array.get().

    //@version=5
    indicator("My script", overlay=true)
    
    string myString = "Hello"
    myStringArr = str.split(myString, '')
    secondChar = array.get(myStringArr, 1)
    
    if (barstate.islast)
        label.new(bar_index, high, secondChar)
    

    enter image description here