From fe3844f5446160f3663d7c5f2ef5930c083fdf0a Mon Sep 17 00:00:00 2001 From: Abdullah Javed Nesar Date: Sat, 30 Apr 2022 23:16:22 +0530 Subject: [PATCH] Implementation for negative indexing in str --- integration_tests/test_str_01.py | 2 ++ src/runtime/impure/lfortran_intrinsics.c | 7 +++++++ 2 files changed, 9 insertions(+) diff --git a/integration_tests/test_str_01.py b/integration_tests/test_str_01.py index 5752c3267a..7da6cd83bc 100644 --- a/integration_tests/test_str_01.py +++ b/integration_tests/test_str_01.py @@ -24,6 +24,8 @@ def test_str_index(): a: str a = "012345" assert a[2] == "2" + assert a[-1] == "5" + assert a[-6] == "0" def check(): f() diff --git a/src/runtime/impure/lfortran_intrinsics.c b/src/runtime/impure/lfortran_intrinsics.c index 7b4747c6bb..63f8b2535d 100644 --- a/src/runtime/impure/lfortran_intrinsics.c +++ b/src/runtime/impure/lfortran_intrinsics.c @@ -616,6 +616,13 @@ LFORTRAN_API void _lfortran_strcat(char** s1, char** s2, char** dest) // idx1 and idx2 both start from 1 LFORTRAN_API char* _lfortran_str_copy(char* s, int32_t idx1, int32_t idx2) { + int s_len = strlen(s); + if(idx1 <= 0) { + idx1 = s_len + idx1; + } + if(idx2 <= 0) { + idx2 = s_len + idx2; + } char* dest_char = (char*)malloc(idx2-idx1+2); for (int i=idx1; i <= idx2; i++) {