Java基础——常用对象API(1):String类

1.String类的特点

字符串对象一旦被初始化就不会被改变
字符串存储在字符串常量池,池中没有,就建立;有,就直接用

String s1 = "Java";//在常量池中创建1个对象,可以被共享
String s2 = new String("Java");//在堆中创建2个对象:1个new1个字符串常量在堆内存中

s1==s2; //false
s1.equals(s2);//true

PS:String类中的equals比较的是字符串中的内容,而不是地址


2.String类的构造函数

String s0 = new String("");//等效String s0 = "";不等效String s0 = null;

byte[] arr0 = {97,66,67,68};
String s1 = new String(arr0);
System.out.println("s1="+s1);//s1=aBCD

char[] arr1 ={'k','h','b','t','e'};
String s2 = new String(arr1);
System.out.println("s2="+s2);//khbte

char[] arr2 ={'I','h','c','t','A','q'};
String s3 = new String(arr2,2,1);
System.out.println("s3="+s3);//c

3.常见功能

3.1 获取

3.1.1 获取字符串中字符的长度

int length()

String s4 = "11sfafgdghs";
System.out.println("length:"+s4.length());//11

3.1.2 根据位置获取字符

char charAt(int index)

String s5 = "75wrtgdgw";
System.out.println("charAt:"+s5.charAt(6));//d
System.out.println("charAt:"+s5.charAt(20));//StringIndexOutOfBoundsException

3.1.3 根据字符,获取其在字符串中第一次出现的位置

int indexOf(int ch)
根据字符,在指定位置获取其在字符串中第一次出现的位置
int indexOf(int ch,int fromIndex)
根据字符串,获取其在字符串中第一次出现的位置
int indexOf(String str)
根据字符串,在指定位置获取其在字符串中第一次出现的位置
int indexOf(String str,int fromIndex)

从后面
int lastIndexOf(int ch)
int lastIndexOf(int ch,int fromIndex)
int lastIndexOf(String str)
int lastIndexOf(String str,int fromIndex)

String s6 = "75wrtwrtgd7gw";
System.out.println("indexOf:"+s6.indexOf('7'));//0
System.out.println("indexOf:"+s6.lastIndexOf('7'));//10

System.out.println("indexOf:"+s6.indexOf('7',2));//第2次出现7的位置:10
System.out.println("indexOf:"+s6.indexOf('8'));//-1
System.out.println("indexOf:"+s6.indexOf("w"));//2
System.out.println("indexOf:"+s6.indexOf(100));//9
System.out.println("indexOf:"+s6.indexOf("wrt"));//2
System.out.println("indexOf:"+s6.indexOf("gdsg"));//-1
System.out.println("indexOf:"+s6.indexOf("wrt",3));//5

3.1.4获取字符串中的一部分字符串

String substring(int beginIndex,int endIndex)
String substring(int beginIndex)

3.2 转换

3.2.1 将字符串变成字符串数组(字符串的切割)

String[ ] split (String regex) :涉及到正则表达式

String s8 = "张三,李四,王五";
        String[] s9 = s8.split(",");
        for (int i = 0; i < s9.length; i++) {
            System.out.println(s9[i]);
        }
        //张三
        //李四
        //王五
String s10 = "张三.李四.王五";
        String[] s11 = s10.split("\\.");
        for (int i = 0; i < s9.length; i++) {
            System.out.println(s10[i]);
        }
        //张三
        //李四
        //王五    

3.2.2 将字符串变成字符数组

char[] toCharArray(String str)

String s12 = "1,23gs";
        char[] c = s12.toCharArray();
        for(int i = 0; i < c.length; i++) {
            System.out.println(c[i]);
        }
        //1
        //,
        //2
        //3
        //g
        //s

3.2.3 将字符串变成字节数组

String s13 = "3A,b";
        byte[] bytes = s13.getBytes();
        for(int i = 0; i < bytes.length; i++) {
            System.out.println(bytes[i]);
        }
        //51
        //65
        //44
        //98

3.2.4 将字符串中的字母转成大小写

String toUppercase():转成大写
String toLowerCase():转成小写

String s14 = "qwKJqUYgn";
        String s15 = s14.toUpperCase();
        String s16 = s14.toLowerCase();
        System.out.println(s15);//QWKJQUYGN
        System.out.println("qwKJqUYgn".toUpperCase());//QWKJQUYGN
        System.out.println("qwKJqUYgn".toLowerCase());//qwkjquygn
        System.out.println(s16);//qwkjquygn

3.2.5 将字符串中的字母替换

String replace(char oldChar,char newChar);
String replace(Stringr oldString,String newString);

System.out.println("jovo".replace('o','a')); //java
System.out.println("jovo".replace('q','a'));//jovo
System.out.println("qwerakdjzzxcj".replace("qwer","542"));//542akdjzzxcj

String s17 = "java";
String s18 = s17.replace('a','o');
String s19 = s17.replace('q','o');
System.out.println(s17==s18);//false
System.out.println(s17==s19);//true

3.2.6 将字符串两端的空格去除

System.out.println("  re 1ghg j    - ".trim());//re 1ghg j    -
System.out.println("  re 1ghg j    - ");       //  re 1ghg j    - 

3.2.7 将字符串进行连接

System.out.println("qw".concat("1d"));//qw1d
System.out.println("qw"+"1d");//qw1d

3.3 判断

3.3.1 判断字符串内容是否相同

boolean equals(Object obj)
boolean equalsIgnoreCase(String anotherString) //忽略大小写

String s20 = "asd";
System.out.println(s20.equals("ASD"));//false
System.out.println(s20.equals("ASD".toLowerCase()));//true
System.out.println(s20.toUpperCase().equals("ASD"));//true
System.out.println(s20.equalsIgnoreCase("ASD"));//true

3.3.2 判断字符串中是否包含指定字符串

boolean contains(String str)

String s21 = "aswrffd";
System.out.println(s21.contains("ff"));//true
System.out.println(s21.contains("dd"));//false

3.3.3 判断字符串是否以指定字符串开头,以指定字符串结尾

boolean startsWith(String str)
boolean endsWith(String str)

String s22 = "java.demo.com";
System.out.println(s22.startsWith("java"));//true
System.out.println(s22.endsWith("com"));//true
System.out.println(s22.contains("demo"));//true

3.4 比较

int compareTo(String str)

System.out.println("A".compareTo("a"));//-32
System.out.println("Ac".compareTo("ad"));//-32

4.String类练习

4.1 字符串数组排序

import com.sun.org.apache.bcel.internal.generic.SWAP;

public class Test1 {
    public static void main(String[] args) {
        String[] s = {"nba","abc","cba","zz","qq","haha"};

//        插入排序
//        for (int i = 1; i < s.length; i++) {
//            String temp = s[i];
//            int q = i;
//            for ( ; q>0&&temp.compareTo(s[q-1])<0; q-- ) {
//                s[q] = s[q-1];
//            }
//            s[q] = temp;
//        }

        for(int i = s.length-1; i > 0; i--) {
            int flag = 1;
            for(int j = 0; j < i; j++) {
                if(s[j].compareTo(s[j+1])>0) {
                    swap(s,j,j+1);
                    flag = 0;
                }
            }
            if(flag==1) break;
        }

        System.out.print("[");
        for(int i = 0; i < s.length; i++) {
            if(i!=s.length-1) {
                System.out.print(s[i]+", ");
            }
            else{
                System.out.print(s[i]+"]");
            }
        }
    }

    //冒泡排序swap函数
    public static void swap(String[] s, int i, int j) {
        String temp = s[i];
        s[i] = s[j];
        s[j] = temp;
    }
}

4.2 子串的次数

public class Test2 {
    public static void main(String[] args) {
        String s = "nnbab44nba5644nbaNba";
        String findS = "nba";

        System.out.println(getCount(s,findS));
    }

    public static int getCount(String s, String findS) {
        int from = 0;
        int cnt = 0;

        while (s.indexOf(findS,from)!=-1) {
            cnt++;
            from = s.indexOf(findS,from)+findS.length();
        }

        return cnt;
    }
}

4.3 最大相同字串

public class Test3 {
    public static void main(String[] args) {
        String a = "jkfnajabcdefggda";
        String b = "abcdef";

        System.out.println(getMaxSubstring(a,b));


    }

    public static String getMaxSubstring(String a,String b) {
        String s0;
        String s1;

        //统一将s0作为短的一方
        if ( a.length() >= b.length() ) {
            s0 = b; //短
            s1 = a;//长
        } else {
            s0 = a; //短
            s1 = b;//长
        }

        for (int i = 0; i < s0.length(); i++) {

            //k<=s0.length()取到“=”是因为substring(a,b)取的区间是[a,b)
            for (int j = 0, k = s0.length() - i; k <= s0.length() ; j++, k++) {

                if (s1.contains(s0.substring(j, k))) {

                    return s0.substring(j, k);
                }
            }
        }

        return null;
    }
}

4.4 模拟trim方法

public class Test4 {

    public static void main(String[] args) {
        String s = "    dgkj fdgi    ";

        System.out.println("-"+myTrim(s)+"-");
    }

    public static String myTrim(String s) {
        int start = 0;
        int end = s.length()-1;

        while(start<=end && s.charAt(start)==' ') {
            start++;
        }
        while(start<=end && s.charAt(end)==' ') {
            end--;
        }

        return s.substring(start,end);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
HDFS是Hadoop分布式文件系统,它提供了Java API来进行文件读写操作。在HDFS中,文件被分成多个块并存储在不同的节点上,因此需要使用分布式文件系统的API来进行文件读写操作。 HDFS Java API提供了以下几个来进行文件读写操作: 1. FileSystem:表示一个文件系统对象,可以通过它来获取文件系统的配置信息、创建文件、删除文件等操作。 2. Path:表示一个文件或目录的路径。 3. FSDataInputStream:表示一个输入流,可以用来读取HDFS中的文件。 4. FSDataOutputStream:表示一个输出流,可以用来向HDFS中写入数据。 下面是一个简单的示例代码,演示如何使用HDFS Java API进行文件读写操作: ```java import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FSDataOutputStream; public class HdfsExample { public static void main(String[] args) throws Exception { // 创建一个Configuration对象,用于获取Hadoop配置信息 Configuration conf = new Configuration(); // 获取HDFS文件系统对象 FileSystem fs = FileSystem.get(conf); // 创建一个Path对象,表示要读取的文件路径 Path inputPath = new Path("/input/test.txt"); // 创建一个FSDataInputStream对象,用于读取文件 FSDataInputStream in = fs.open(inputPath); // 读取文件内容 byte[] buffer = new byte[1024]; int len = in.read(buffer); while (len > 0) { System.out.write(buffer, 0, len); len = in.read(buffer); } // 关闭输入流 in.close(); // 创建一个Path对象,表示要写入的文件路径 Path outputPath = new Path("/output/test.txt"); // 创建一个FSDataOutputStream对象,用于写入文件 FSDataOutputStream out = fs.create(outputPath); // 写入文件内容 String content = "Hello, HDFS!"; out.write(content.getBytes()); // 关闭输出流 out.close(); } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值