前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >java中String类的用法

java中String类的用法

作者头像
马克java社区
修改2021-03-17 10:12:33
4980
修改2021-03-17 10:12:33
举报
文章被收录于专栏:java大数据

1.String

String类很常用,很重要。

String不像int或float, 它是参考类型。final类型, 不能被继承,String is a Reference Type,Defined in java.lang package

常用方法:

length()

String greeting = “Hello”;

int n = greeting.length();//is 5

charAt(n)(取某个位置字符)

char first = greeting.charAt(0);

char last = greeting.charAt(4);

substring()(取子字符串)

String s = greeting.substring(0,3);//from 0 inclusive to 3 exclusive

Concatenation(链接)

String a = greeting + “ world!”+ 2009;

Equality(don’t use ==)(测试是否相等)

String s = “Hello”; s.equals(greeting);

“Hello”.equalsIgnoreCase(“hello”);(忽略大小写的测试相等)

例子:

public class Test {

    public static void main(String args[]) {

        String letters = "abcdefghijklabcdefghijkl";

/*这里讲讲阅读源代码,control点击进入方法*/

        System.out.println("'c'在第" + letters.indexOf('c') + "个");

/* indexOf(int ch, int fromIndex) Returns the index within this string

of the first occurrence of the specified character, starting the

search at the specified index.*/

        System.out.println("'a'在第" + letters.indexOf('a', 1) + "个");

        System.out.println("'$'在第" + letters.indexOf('$') + "个");

        System.out.println("def在第" + letters.indexOf("def") + "个");

        System.out.println("'c'在第" + letters.lastIndexOf('c') + "个");

        System.out.println(letters.substring(20));// 从第20个到末尾

/*beginIndex - the beginning index, inclusive(包含). endIndex - the ending

index, exclusive(不包含).*/

        System.out.println(letters.substring(3, 6));

    }

 

 

public class Test {

    public static void main(String args[]) {

        String s, s1;

        char charArray[] = new char[8];

        s1 = new String("Hello World!");

        // s1 = "Hello World!";

        // 输出String的长度

        System.out.println(s1.length());

        s1=s1.replace("World", "mark-to-win");

        System.out.println("s1 is "+s1);

        // 使用charAt()翻转字符串

        s = "";

        for (int i = s1.length() - 1; i >= 0; i--)

            s = s + s1.charAt(i);

        System.out.println(s);

    }

}

String表示字符串常量:一旦创建后不会再做修改和变动的字符 串。之所以采用这种方法是因为实现固定的,不可变的字符串比实现可变的字符串更简单高效。对于那些想得到改变的字符串的情况,有一个叫做 StringBuffer的String类的友类。它的对象包含了在创建之后可被改变的字符串。String类和StringBuffer类都在 java.lang包中定义。

更多请见:https://blog.csdn.net/qq_44639795/article/details/101773979

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档