0

Someone often writes like this when extracting characters one by one from the beginning to the end of a string.

For example:

function rev1(str,    i, ret) {
    for (i = 1; i <= length(str); i++) {
        ret = substr(str, i, 1) ret;
    }
    return ret;
}

I think don't necessarily have to use the length().

function rev2(str,    ch, i, ret) {
    while (ch = substr(str, ++i, 1)) {
        ret = ch ret;
    }
    return ret;
}

It works, but is it wrong?

1
  • if str was an array, so second function will be fail Commented Feb 3, 2020 at 6:47

1 Answer 1

0

You're not wrong (assuming it's input really is a string and not an array), but the resulting code is less clear since it's relying on the condition doing a string comparison since the return from substr() is a string. At a glance I thought it'd fail if the string contained a 0 but it won't thanks to that string comparison being enforced.

3
  • I thank you. I recently came up with this little algorithm. rev1() extracts characters one by one from a "whole string". So it was irrational to get the length of the string, I thought. In our country, we usually use multi-byte characters. Thus using length () in GAWK is pretty heavy and slow. Commented Feb 4, 2020 at 1:56
  • For efficiency you wouldn't REALLY call length(str) in every iteration of the loop like in the code you posted, you'd call it once before the loop and set a variable as in n = length(str); for (i=1; i<=n; i++). It's hard to believe calling length() would be heavy and slow given that. Since you mention you're using gawk though you could do n=split(str,arr,""); for (i=1; i<=n; i++) ret = arr[i] ret and so exchange both length() and substr() calls for one call to split(). idk which would be faster but you could try it. Commented Feb 4, 2020 at 2:07
  • 1
    Thank you for your kindness. I know.Initialization only once.If rev1() works millions times then Millions of uses of length () for millions of data would seem irrational. Commented Feb 4, 2020 at 2:22

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.