开发者社区> 问答> 正文

Java里String字符串获取功能的方法有哪些呀?

已解决

Java里String字符串获取功能的方法有哪些呀?

展开
收起
gxx1 2022-04-02 21:55:36 762 0
1 条回答
写回答
取消 提交回答
  • 推荐回答

    1、获取字符串的长度

    // 创建字符串对象

    String s1 = "hello-world!";

    // 我们来获取字符串长度

    int length = s1.length();

    System.out.println("s1字符串的长度是:" + length);

    输出结果:

    s1字符串的长度是:12

    2、拼接字符串

    String s1 = "hello-world!";

    // s1字符串的末尾拼接上hello-dkt

    String s2 = s1.concat("hello-dkt");

    System.out.println("拼接后的字符串s2:" + s2);

    输出结果:

    拼接后的字符串s2:hello-world!hello-dkt

    3、获取指定字符串的索引

    String s1 = "hello-world!";

    // 获取s1中索引值为1的字符

    char c = s1.charAt(1);

    System.out.println("索引值为1的字符" + c);

    输出结果: 索引值为1的字符e

    4、返回指定字符串第一次出现在该字符串内的索引

    // 创建一个比较长的字符串对象

    String s3 = "hello-world-hello-dkt-hello-Java-hello-lang";

    // 查找hello第一次出现在s3中的索引位置

    int index1 = s3.indexOf("hello");

    System.out.println("hello第一次出现在s3中的索引值位置:" + index1);

    // 查找hello第二次出现在s3中的索引位置

    int index2 = s3.indexOf("hello",index1+1);

    System.out.println("hello第一次出现在s3中的索引值位置:" + index2);

    输出结果:

    hello第一次出现在s3中的索引值位置:0

    hello第一次出现在s3中的索引值位置:12

    5、截取字符串

    // 创建一个比较长的字符串对象

    String s3 = "hello-world-hello-dkt-hello-Java-hello-lang";

    // 获取所以12以后的字符串

    String s4 = s3.substring(12);

    System.out.println("截取字符串:" + s4);

    输出结果: 截取字符串:hello-dkt-hello-Java-hello-lang

    6、截取中间字符串

    // 创建一个比较长的字符串对象

    String s3 = "hello-world-hello-dkt-hello-Java-hello-lang";

    // 截取索引12--16之间的字符串

    String s5 = s3.substring(12,26);

    System.out.println("截取中间字符串:" + s5);

    输出结果: 截取中间字符串:hello-dkt-hell

    上述代码都运用了字符串的功能,我们可以将其作为参考进行应用。

    2022-04-02 22:00:33
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载