Search code examples
j

Replace atom in array of strings


Suppose I have an array of strings "31,793.1" "29,798.6" "30,455.7" "29,700.9"

How do I replace , with nothing to give me "31793.1" "29798.6" "30455.7" "29,700.9"

Another example is to replace - in "-5" "-3" "-4" with _ to give "_5" "_3" "_4" .


Solution

  • "31,793.1" "29,798.6" "30,455.7" "29,700.9" would not be an "array of strings" in J. I will suppose that you have a line like this and you want to end up with an array of numbers:

    data =: '"31,793.1" "29,798.6" "30,455.7" "29,700.9" "-5"'
    
    NB. Convert commas to "null" and '-'s to '_'s
    NB. rplc works in pairs 'old';'new'
    data rplc ',';'';'-';'_'
    "31793.1" "29798.6" "30455.7" "29700.9" "_5"
    
    NB. remove '"'s
    data rplc '"';''
    31793.1 29798.6 30455.7 29700.9 _5
    

    Normally now you would have to split on whitespace (there are many ways to do this) but converting to numbers using ". takes care of this here:

     NB. ". data
     31793.1 29798.6 30455.7 29700.9 _5
    
     +/ data
     121743