常见的几种获取字符串的方法

常见的几种获取字符串的方法

获取字符串的长度

length()方法会返回字符数量,获取字符串长度,也就是char的数量

String n='1234';
int size=n.length();//获取字符串的长度

 

获取指定位置的字符

charAt(int index)方法用来获取指定索引的字符

复制代码
public class charAt
{
    public  static void main(String []args)
    {
        String str="这是第三次的博客";
        char ch=str.charAt(5);
        System.out.println(ch);//获取的就是三
    }
}
复制代码

 

获取子字符串索引的位置

indexOf()方法返回的是搜索的字符或字符串在字符串中首次出现的索引位置,如果没有检索到要查找的字符/串,则返回-1

String str='The best wishes to you';
int size=str.indexOf('e'); //查找的是e首次出现的位置,即2

 

判断字符串首尾内容

startsWith()方法和endWith()方法分别用于判断字符串是否以指定的内容开始或结束,其返回值都为boolean类型

复制代码
public class startsWith {
    public static void main (String []args)
    {
        String src[]={"高","山","仰","止","景","行","行","止"};
        int n=0;
        for(int i=0;i<src.length;i++)
        {
             String pose=src[i];
            if(pose.startsWith("止"))
            {
                n++;
            }
        }
        System.out.print("共有"+n+"个止");
    }
}
复制代码

 

复制代码
public class endwith{
    public static void main (String []args)
    {
        String id[]={'123','241','258','456'};
        String num='1';
        System.out.println("学号末尾为"+num+"的是: ");
        for(int i=0;i<id.length;i++)
        {
            if(id[i].endWith(num))
            {
                System.out.print(id[i]);
            }
        }
    }
    
}
​
复制代码

 

获取字符数组

toCharArray()方法可以将字符串转换为一个字符数组

复制代码
public class StringToArray
{
    public static void main(String [] args)
    {
        String src="太阳依旧会升起,哪怕照亮的只是废墟!";
        char[]ch=src.toCharArray();
        for(int i=0;i<ch.length;i++)
        {
            System.out,println("数组第"+i+"个元素为:"+ch[i]);
        }
    }
}
复制代码

 

判断字符串是否存在

contains()方法可以判断字符串中是否包含指定的内容

复制代码
public class StringContains{
    public static void main(String []args)
    {
        String src="校园四霸:绫小路清隆,折木奉太郎,比企谷八幡,梓川咲太";
        System.out.print(src);
        boolean request1=src.contains("绫小路清隆");
        System.out.print("校园四霸中有绫小路清隆吗?"+request1);
        boolean request2=src.contains("桐谷和仁");
          System.out.print("校园四霸中有桐谷和仁吗??"+request2);
    }
}
 
复制代码

 

posted @   ShamUnite  阅读(1479)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示