String 中与获取字符串常用的方法有:
- public int length() 获取字符串的长度。
String a ="sdklc mdfas";
System.out.println("字符串的长度为:"+a.length());
- public String concat(String str) 将当前字符串和参数字符串拼接为一个新的字符串。(由于String具有不可更改性,所以想要两个字符串在一起时可以用concat)
String str = "我是世界上";
String str2 = "最可爱的人";
String str3 =str.concat(str2);
System.out.println(str3);
- public char charAt( int a ) 获取指定索引位置的单个字符。
String str4 = "adasdasdvsc";
System.out.println("在第5号索引位置的字母是"+str4.charAt(5));
4.public int indeof(String str) 查找参数字符串在本字符串中第一次出现的索引位置,如果没有返回 -1值。
String original = "ABCDeFGeeeee";
System.out.println("e在字符串中第一次出现的索引位置是:"+original.indexOf("e"));
字符串从大的字符串截取小的字符串的方法:
两种重载方式:
- public String substring(int index) index是索引的意思,获取从参数索引位置的字符到最后。
- public String substring(int index, int index),获取从左参数索引位置到右参数索引位置前一个,即左闭右开。
String str = "helloword";
//现在我只想要word
//1.用indexof(想要找的东西)
String str2 = str.substring(str.indexOf("w"));
//2.直接输入索引位置
String str3 = str.substring(5);
//3.[左索引位置,右索引位置)不包含右边索引
String str4 = str.substring(5,9);
System.out.println(str4);
ps:双引号下的字符串是不可以改变的
String a ="abc" ;
System.out.println(System.identityHashCode(a));
a ="cba";
System.out.println(System.identityHashCode(a));
内容未改变但是地址值发生了改变。
字符串转换的方法:
- public char[ ] toCharArray() 转换成字符数组。
- public byte[ ] getBytes(); 转换成一个字节数组。
- public String replace(Charsequence oldString,Charsequence newString) 将字符串中原有的转换为新的放在一个新字符串中。
String oldString ="你大爷的";
String newString = oldString.replace("大爷", "**");
System.out.println(newString);
字符串的分割方法:
1.public String[ ] Spolit(String regex) 里面是一个正则表达式,遇到 英文中的点 “.”时 注意加前面加//