String类使用方法

时间:2023-04-20 09:42:38

1.1、字节与字符串相互转换

    |-字节-->String:public String(byte[]  bytes)

       |-String-->字节: public byte[] getBytes(String charsetName)

范例:字节-->字符串

public class Demo1 {

public static void main(String[] args) {

String str="hello world";

byte []b=str.getBytes();

byte []c={66,67,68,69,70,71};      //定义一个byte字节的数组c

String str1=new String(b);         //将b数组转换为字符串型

String str2=new String(c);         //将c数组转换为字符串型

System.out.println(str1);

System.out.println(str2);

}

}

1.2、判断是否以某字符开头,或结尾

|-以某字符结尾:public boolean endsWith(String suffix)

|-以某字符开头:public boolean startsWith(String prefix)

范例:

public class Demo2 {

public static void main(String[] args) {

String str="Hello world";

System.out.println(str.startsWith("h"));      //如果是以h开头,则返回true

System.out.println(str.endsWith("d"));

}

}

 

1.3、替换操作

|-全部替换public String replaceAll(String regex, String replacement)

public class Demo2 {

public static void main(String[] args) {

String str="Hello world";

System.out.println(str.replaceAll("o", "x"));    //将字符串中的o代替为x

}

}


1.4、替换操作

|-字符串截取public String substring(int beginIndex)

public class Demo2 {

public static void main(String[] args) {

String str="Hello world";

String str1=str.substring(0, 5);       //从0下标开始截取5个字符

System.out.println(str1);

}

}

1.5、拆分操作

|-字符串拆分:public String[] split(String regex)

public class Demo2 {

public static void main(String[] args) {

String str="Hello world";

String[] str1=str.split(" ");      //将字符串按“ ”(空格)拆分为字符串数组

for (String string : str1) {

System.out.print(string+",");   //打印拆分后的字符串数组

}

}

}

1.6、查找操作

      |-public int indexOf(int ch, int fromIndex)、public int indexOf(int ch)
       |-此方法返回int整数型,如果查找到了,则返回位置,没有查找到则返回-1;

public class Demo2 {

public static void main(String[] args) {

String str="Hello world";

System.out.println(str.indexOf("l"));     //查找l的位置,如果string中有“l“,则返回其在string中的位置;没有,则返回-1

}

}


1.7、字符串的其他操作

去掉左右空格:public String trim()

取得字符串长度:public int length()

小写转大写:public String toUpperCase(Locale locale)

大写转小写:public String toLowerCase(Locale locale)

操作练习

         判断邮箱地址是否正确;(是否有“@”及“.”符号)

public class Demo3 {

public static void main(String[] args) {

String str="abc@134.com";

if(str.indexOf("@") == -1 && str.indexOf(".")==-1){

System.out.println("你输入的邮箱不合法");

}else{

System.out.println("合法邮箱");

}

}

}