zoukankan      html  css  js  c++  java
  • Codewars Solution:String ends with?

    Level 7kyu :String ends with?

    完成解决方案,以便如果传入的第一个参数(字符串)以第二个参数(也是字符串)结尾,则返回true。

    该题考查判断字符串以什么结尾。

    两个解决方案:

    1、循环

    主要方法:

    charAt(索引)->String某个位置的字符

    length()->String长度

    2、String函数

    endsWith(指定字符串)->字符串是否以指定字符串结尾

    public class Kata {
      public static boolean solution(String str, String ending) {
        int strL=str.length();//获取两个字串长度
        int endingL=ending.length();
        int j=1;
        if(strL>=endingL) {//判断第二个参数的长度是否规范(后来加上的)
          for(int i=endingL-1;i>=0;i--,j++){//两个索引同时向前移动,移动长度为第二个参数长度
            if(ending.charAt(i)!=str.charAt(strL-j)) {
              return false;
            }
          }
        }else{
          return false;
        }
        return true;
      }
    }

    循环总结:第一次点击TEST测试用例的时候成功pass,但是ATTEMPT的时候报错了,原因是数组下标越界,没考虑到第二个参数长度。

    1 public static boolean solution(String str, String ending) {
    2     if(str.endsWith(ending)) {//字符串是否以指定字符串结尾
    3         return true;
    4     }
    5     return false;
    6 }

    函数总结:除了endsWith(),还有startsWith()->以指定字符串开始,参数可有可无,有则是指定索引处开始的子字符串是否以指定前缀开始。

    最后:其他人的解决办法

    1、字符串截取,substring出来比较两个字符串

    public class Kata {
      public static boolean solution(String str, String ending) {
        if(str.length() < ending.length()) {
          return false;
        } 
        else {
          return str.substring(str.length() - ending.length()).equals(ending);
        }
      }
    }

    2、toCharArray()其实类似与charAt()

  • 相关阅读:
    @JsonFormat和@DateTimeFormat 实践测试
    spring jpa CrudRepository save 新建数据没有返回id
    多线程处理pdf附件转换
    contentsize ,ios 7和 ios7之前的 有点差别,
    区别,
    裁切图片,
    transform,
    简洁代码,
    这个系统,流程,入口,业务逻辑,
    pop,pop,如果break,会pop两次,
  • 原文地址:https://www.cnblogs.com/mc-web/p/12995381.html
Copyright © 2011-2022 走看看