Skip to content

Commit 8f42086

Browse files
committed
GROOVY-11636: Create a SGM#next method which also takes an integer increment value
1 parent d77d909 commit 8f42086

1 file changed

Lines changed: 41 additions & 0 deletions

File tree

src/main/java/org/codehaus/groovy/runtime/StringGroovyMethods.java

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1981,6 +1981,47 @@ public static String next(final CharSequence self) {
19811981
return buffer.toString();
19821982
}
19831983

1984+
/**
1985+
* A variant of next with an integer count parameter; equivalent to calling next() count times.
1986+
* <pre class="groovyTestCase">
1987+
* assert 'a'.next(1) == 'a'.next()
1988+
* assert 'a'.next(4) == 'e'
1989+
* assert 'a'.next(0) == 'a'
1990+
* assert 'a'.next(25) == 'z'
1991+
* assert 'A'.next(32) == 'a'
1992+
* assert (0..4).collect('a'::next) == 'a'..'e'
1993+
* assert 'car'.next(2) == 'cat'
1994+
* </pre>
1995+
*
1996+
* @param self a CharSequence
1997+
* @oaram n how many times to increment
1998+
* @see #next(CharSequence)
1999+
* @return a value obtained by incrementing the toString() of the CharSequence n times
2000+
*
2001+
* @since 5.0.0
2002+
*/
2003+
public static String next(final CharSequence self, int n) {
2004+
if (n < 0) {
2005+
throw new IllegalArgumentException("A negative value for n is not supported");
2006+
}
2007+
StringBuilder buffer = new StringBuilder(self);
2008+
if (buffer.length() == 0) {
2009+
buffer.append(Character.MIN_VALUE);
2010+
} else {
2011+
char last = buffer.charAt(buffer.length() - 1);
2012+
for (; n > 0; n--) {
2013+
if (last == Character.MAX_VALUE) {
2014+
buffer.append(Character.MIN_VALUE);
2015+
last = Character.MIN_VALUE;
2016+
} else {
2017+
last++;
2018+
}
2019+
}
2020+
buffer.setCharAt(buffer.length() - 1, last);
2021+
}
2022+
return buffer.toString();
2023+
}
2024+
19842025
/**
19852026
* Returns a String with linefeeds and carriage returns normalized to linefeeds.
19862027
*

0 commit comments

Comments
 (0)