Java day3【第十一章】String常用方法

北战南征 提交于 2019-12-01 10:16:00

一.String常用方法:

2.字符串与字符

(1)字符串与字符数组:

  为了博客简洁,省略前面代码:

String str = "www.hao123.com";
char c = str.charAt(5);        //输出 a

  将字符串转换为字符数组:

String str = "www.hao123.com";
char [] result = str.toCharArray();

(2)字符串与字节数组:

 

 

public class Stringdemo{
	public static void main(String args[]) {
		String str = "helloworld";
		byte date[] = str.getBytes();
		for (int x = 0;x<date.length ; x++)
		{
			date[x] -= 32;
		}
		System.out.println(new String(date));
		}
}

  

 3.字符串的操作:

(1)字符串比较:

  String.equals()

String strA = "www.mldn.com";
String strB = "www";
System.out.println(strA.equals(strB));

  String.equalsIgnoreCase()      //不区分大小写:

String strA = "www.mldn.com";
String strB = "www";
System.out.println(strA.equalsIgnoreCase(strB));

  String.compareTo()

String sta = "A";
String stb = "a";
System.out.println(sta.compareTo(stb));          //输出-32    大小写ASCLL码相差32

(2)字符串查找:

  String.contains()       包含,返回布尔值

String sta = "helloworld";
String stb = "hello";
System.out.println(sta.contains(stb));      //返回true

  String.indexOf()      查找索引

String sta = "helloworld";
String stb = "hello";
System.out.println(sta.indexOf(stb));      //返回0,代表stb从sta索引为0的位置开始

  String.lastIndexOf() 

String sta = "hello.world.";
String stb = ".";
System.out.println(sta.lastIndexOf(stb));    //返回11,从后往前查找

  String.startswith()  判断以什么开始

  String.endswith()   判断以什么结束

(3)字符串的替换:

  String.replaceAll()   替换所有字符

strA = stra.replace("k","l")

  String.replaceFirst()  替换首个字符

(4)字符串截取:

  String.substring(int index)

  String.substring(int beginindex int endindex)

(5)字符串格式化:

  占位符:String(%s)  字符(%c)  整数(%d)  小数(%f)

  String.format()

4.其他操作方法:

(1)

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!