zoukankan      html  css  js  c++  java
  • 字符串查找

    示例1:

    public int indexOf(String str)    从头开始查找指定字符串的位置,查找到了返回位置开始的索引,如果查找不到返回-1

    public class StringDemo {
        public static void main(String[] args) {
            String str = "helloworld";
            System.out.println(str.contains("world"));  //判断一个子字符串是否存在
        
            System.out.println(str.indexOf("world"));  //5,w开始的索引
            System.out.println(str.indexOf("java"));   //-1,没有查找到
            if(str.indexOf("world") != -1){
                System.out.println("可以查找到指定内容!");
            }
    
        }
    }

    输出1:

    true
    5
    -1
    可以查找到指定内容!

    示例2:

    但是现在基本上都建议使用contains()方法完成。

    但是indexOf()需要注意的是,如果内容重复,它只能够返回查找的第一个位置。

    public class 字符串查找 {
        public static void main(String[] args) {
           String str = "helloworld";
           System.out.println(str.indexOf("l"));
           System.out.println(str.indexOf("l",5));
           System.out.println(str.lastIndexOf("l"));
        }
    }

    示例3:

    在进行查找的时候往往会判断开头或结尾。

    public class 字符串查找 {
        public static void main(String[] args) {
            String str = "**@@helloworld##";
            System.out.println(str.startsWith("**"));
            System.out.println(str.startsWith("@@",2));
            System.out.println(str.endsWith("##"));
        }
    }

    输出3:

    true
    true
    true
  • 相关阅读:
    vim编辑中断后,重新编辑的警告删除
    更新centos7的kernel
    centos7 设置连接无线wifi
    U盘安装centos7
    centos7清理矿机木马qw3xT,kpgrbcc
    centos7 防火墙屏蔽IP
    ftp用户和密码
    聚类结果的评估指标及其JAVA实现
    java.io.Serializable浅析
    JAVA中求解对象所占字节大小
  • 原文地址:https://www.cnblogs.com/yrxns/p/9284383.html
Copyright © 2011-2022 走看看