[英]iterate over string without using string.length
我編寫了該代碼,並且想在不使用s.length
情況下遍歷字符串。 我無法意識到while循環中合適的條件是什么。
int i = 0;
String s = "abcdefg";
while (s.charAt(i) != null) {
System.out.println(s.charAt(i));
i++;
}
沒有理由不使用String的length()方法。 但是,如果您必須:
String s = "abcdefg";
for (Character c : s.toCharArray()) {
System.out.println(c);
}
是的,您可以捕獲IndexOutOfBounds異常,當您嘗試讀取字符串范圍之外的char時引發該異常。 但是使用長度(如果可能?!)會更好。
不知道為什么不能使用長度,但是此解決方案會起作用。
int i = 0;
String s = "abcdefg";
while(true)
{
try
{
system.out.println(s.charAt(i++));
}
catch
{
break;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.