char[] chs = st.toCharArray(); for(int i=0;i<chs.length; i++){ if((" ").equals(chs[i])){ System.out.println(i); } }
chs中有空格,但是語句貌似就沒有執(zhí)行,,求解!for循環(huán)里面的判斷怎么寫?
認(rèn)證0級講師
因為chs的每一個元素是個char,不是String,而" "是一個String, " ".equals(' ')總是false。你的判斷語句改成這樣就可以了:
if (chs[i] == ' ')
另外,如果只是要找空格位置的話,用indexOf就行了:
System.out.println("Hello world".indexOf(' ')); //輸出5