Skip to content

Commit 6127838

Browse files
authored
Merge pull request #18 from PetrPytelka/string_fix_mid_function
String fix mid function
2 parents 31a0c40 + 70e6a92 commit 6127838

3 files changed

Lines changed: 30 additions & 2 deletions

File tree

src/main/java/com/scriptbasic/utility/functions/StringFunctions.java

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package com.scriptbasic.utility.functions;
22

33
import com.scriptbasic.api.BasicFunction;
4+
import com.scriptbasic.interfaces.BasicRuntimeException;
45

56
/**
67
* <p>
@@ -72,6 +73,20 @@ static public String rtrim(final String s) {
7273
return s.replaceAll("\\s*$", "");
7374
}
7475

76+
/**
77+
* Return {@code len} number of characters from the left (the beginning) of the
78+
* string.
79+
*
80+
* @param s parameter
81+
* @param len parameter
82+
* @return return value
83+
*/
84+
@BasicFunction(classification = {com.scriptbasic.classification.String.class,
85+
com.scriptbasic.classification.Utility.class})
86+
static public String left(final String s, final int len) {
87+
return s.length() > len ? s.substring(0, len) : s;
88+
}
89+
7590
/**
7691
* Return a substring from the string that starts at the position
7792
* {@code start} and has a length of {@code len}.
@@ -80,11 +95,15 @@ static public String rtrim(final String s) {
8095
* @param start parameter
8196
* @param len parameter
8297
* @return return value
98+
* @throws BasicRuntimeException incorrect parameter
8399
*/
84100
@BasicFunction(classification = {com.scriptbasic.classification.String.class,
85101
com.scriptbasic.classification.Utility.class})
86-
static public String mid(final String s, final int start, final int len) {
87-
return s.substring(start, start + len);
102+
static public String mid(final String s, final int start, final int len) throws BasicRuntimeException {
103+
if (start < 1) {
104+
throw new BasicRuntimeException("Incorrect value in parameter start: " + start);
105+
}
106+
return s.substring(start - 1, start - 1 + len);
88107
}
89108

90109
/**

src/test/java/com/scriptbasic/testprograms/TestPrograms.java

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,11 @@ public void testStringConcatenation() throws Exception {
160160
codeTest("TestStringConcatenation.bas", "");
161161
}
162162

163+
@Test
164+
public void testStringFunctions() throws Exception {
165+
codeTest("TestStringFunctions.bas", "0189123");
166+
}
167+
163168
@Test
164169
public void testJavaObjectFieldAccess() throws ScriptBasicException, ClassNotFoundException, AnalysisException {
165170
final var e = new TestingExecutor();
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
v = "0123456789"
2+
PRINT left(v,2)
3+
PRINT right(v,2)
4+
PRINT mid(v,2,3)

0 commit comments

Comments
 (0)