欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

Codewars Solution:Get the Middle Character,

来源: javaer 分享于  点击 10371 次 点评:35

Codewars Solution:Get the Middle Character,


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 }

 

相关文章

    暂无相关文章
相关栏目:

用户点评