Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Julia giving me StringIndex error?

Tags:

string

julia

I'm getting a StringIndex error for one particular string out of 10,000 which I am processing. I don't really know what the issue is with this string. I think it is probably a special character issue.

If I println the string then assign it to txt then pass txt to the function, I don't get an error. I am a little baffled.

I am sorry, I can't post the string as it is protected content and even if I did copying and pasting the string somehow removes the source of error. Any suggestions?

like image 884
Francis Smart Avatar asked Apr 06 '20 14:04

Francis Smart


2 Answers

Just to expand. The details of how String is represented in Julia are explained in the Julia manual.

You can use eachindex to get an iterator of valid indices into a String. The reason why it is an iterator is that you cannot efficiently (i.e. in O(1) time) find an index of i-th character in the string. However, you can use isascii function on a String to check if it consists only of ASCII characters (in which case byte and character indices are the same).

Also if you need to get to some specific character in a string you usually need probably more than one character, in which case first, last and chop functions are useful (actually last(first(s, n)) gives you a character at position n; although it is not most efficient - iterating eachindex will allocate less).

like image 78
Bogumił Kamiński Avatar answered Oct 22 '22 05:10

Bogumił Kamiński


In Julia Strings are indexed by bytes rather than characters. You should use for c in str rather than trying to index manually.

like image 4
Oscar Smith Avatar answered Oct 22 '22 04:10

Oscar Smith