KT-968 String should provide an iterator() method
This commit is contained in:
@@ -110,6 +110,23 @@ public class StdlibTest extends CodegenTestCase {
|
||||
} catch (Throwable t) {
|
||||
// System.out.println(generateToText());
|
||||
t.printStackTrace();
|
||||
throw t instanceof Exception ? (Exception)t : new RuntimeException(t);
|
||||
}
|
||||
}
|
||||
|
||||
public void testForInString() throws Exception {
|
||||
loadText("fun foo() : Int { var sum = 0\n" +
|
||||
" for(c in \"239\")\n" +
|
||||
" sum += (c.int - '0'.int)\n" +
|
||||
" return sum" +
|
||||
"}" );
|
||||
final Method main = generateFunction();
|
||||
try {
|
||||
assertEquals(14, main.invoke(null));
|
||||
} catch (Throwable t) {
|
||||
System.out.println(generateToText());
|
||||
t.printStackTrace();
|
||||
throw t instanceof Exception ? (Exception)t : new RuntimeException(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,3 +66,19 @@ inline fun String(stringBuffer : java.lang.StringBuffer) = java.lang.String(stri
|
||||
|
||||
inline fun String(stringBuilder : java.lang.StringBuilder) = java.lang.String(stringBuilder) as String
|
||||
|
||||
/*
|
||||
Iterator for characters of given String
|
||||
*/
|
||||
inline fun String.iterator() : CharIterator = (this as java.lang.String).iterator()
|
||||
|
||||
/*
|
||||
Iterator for characters of given CharSequence
|
||||
*/
|
||||
inline fun java.lang.CharSequence.iterator() : CharIterator = object: jet.CharIterator() {
|
||||
private var index = 0
|
||||
|
||||
public override fun nextChar(): Char = charAt(index++)
|
||||
|
||||
public override val hasNext: Boolean
|
||||
get() = index < length()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
package testString
|
||||
|
||||
import std.io.*
|
||||
import stdhack.test.*
|
||||
|
||||
import junit.framework.*
|
||||
|
||||
class StringTest() : TestCase() {
|
||||
fun testStringIterator() {
|
||||
var sum = 0
|
||||
for(c in "239")
|
||||
sum += (c.int - '0'.int)
|
||||
assertTrue(sum == 14)
|
||||
}
|
||||
|
||||
fun testStringBuilderIterator() {
|
||||
var sum = 0
|
||||
val sb = StringBuilder()
|
||||
for(c in "239")
|
||||
sb.append(c)
|
||||
|
||||
println(sb)
|
||||
|
||||
for(c in sb)
|
||||
sum += (c.int - '0'.int)
|
||||
assertTrue(sum == 14)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user