Level 7kyu :Get the Middle Character
您將得到一個單詞,
您的作業是回傳單詞的中間字符,
要求:
如果單詞的長度是奇數,則回傳中間字符,
如果單詞的長度是偶數,請回傳中間的2個字符,
主要方法:
length()->獲取字串長度
charAt(索引下標)->回傳字串中指定索引處的字符
1 public class MiddleCharacter { 2 3 public static String getMiddle (String word) { 4 // your code 5 int length=word.length(); 6 if(length%2==0){ 7 return word.charAt(length/2-1)+""+word.charAt(length/2);//這里空字串要先加一次,讓結果為字串 8 } 9 return word.charAt(length/2)+""; 10 } 11 }
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/186216.html
標籤:Java
