文章目录
复习java的字符串用法
concat 链接字符串
string1.concat(string2);
"我的名字是 ".concat("Runoob");
charAt 指定位置索引
返回指定索引处的 char 值
charAt(int index)
compareTo 比较
str1.compareTo( str2 );
如果参数字符串等于此字符串,则返回值 0;
如果此字符串小于字符串参数,则返回一个小于 0 的值;
如果此字符串大于字符串参数,则返回一个大于 0 的值。
endsWith()
String Str = new String("菜鸟教程:www.runoob.com");
方法用于测试字符串是否以指定的后缀结束。
Str.endsWith( "runoob" );
startsWith()
功能与endsWith() 相反
getBytes()
getBytes(String charsetName):
使用指定的字符集将字符串编码为 byte 序列,并将结果存储到一个新的 byte 数组中。
getBytes()
使用平台的默认字符集将字符串编码为 byte 序列,并将结果存储到一个新的 byte 数组中。
byte[] Str2 = Str1.getBytes();
Str2 = Str1.getBytes( "UTF-8" );
class Main {
public static void main(String[] args) {
String str = "make a fortune";
byte[] byt = str.getBytes();
for (byte b : byt) {
System.out.println(b);
}
}
}
getChars()
getChars() 方法将字符从字符串复制到目标字符数组
public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
indexOf 返回第一次出现的索引
int indexOf(int ch)
返回指定字符在此字符串中第一次出现处的索引。
replace
replace() 方法通过用 newChar 字符替换字符串中出现的所有 searchChar 字符,并返回替换后的新字符串。
public String replace(char searchChar, char newChar)
split 正则
split() 方法根据匹配给定的正则表达式来拆分字符串。
public String[] split(String regex, int limit)
注意: . 、 $、 | 和 * 等转义字符,必须得加 \\。
注意:多个分隔符,可以用 | 作为连字符。
public class Demo {
public static void main(String args[]) {
String str = "192.168.1.1";
// . 必须得加 转义字符\\
for(String s : str.split("\\.")){
System.out.println(s);
}
}
}
substring
substring() 方法返回字符串的子字符串。
public String substring(int beginIndex)
或
public String substring(int beginIndex, int endIndex)
String Str = new String("www.runoob.com");
System.out.println(Str.substring(4, 10) );
trim 删除多余的空白
trim() 方法用于删除字符串的头尾空白符。
String Str = new String(" www.runoob.com ");
System.out.println( Str.trim() );
toCharArray()
String str = "helloworld";
char[] data = str.toCharArray();// 将字符串转为数组
数组知识点
==与equal
使用 == 和 equals() 比较字符串。
String 中 == 比较引用地址是否相同,equals() 比较字符串的内容是否相同:
格式
// 写法
dataType[] arrayRefVar;
Arrays 类
java.util.Arrays 类能方便地操作数组,它提供的所有方法都是静态的。
具有以下功能:
给数组赋值:通过 fill 方法。
对数组排序:通过 sort 方法,按升序。
比较数组:通过 equals 方法比较数组中元素值是否相等。
查找数组元素:通过 binarySearch 方法能对排序好的数组进行二分查找法操作。
数组扩容
Array.copy(E[] e,newLength);
其第一个形参指的是需要扩容的数组,后面是扩容后的大小,其内部实现其实是使用了 System.arrayCopy();
在内部重新创建一个长度为 newLength 类型是 E 的数组。
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] a= {10,20,30,40,50};
a= Arrays.copyOf(a,a.length+1);
for(int i=0;i<a.length;i++) {
System.out.println(a[i]);
}
}
}
默认补 0,输出结果为: 10 20 30 40 50 0
比较骚打印二维数组
int[][] array=new int[3][3];
array[1][1]=4;
array[2][1]=5;
for (int[] ints : array) {
for (int anInt : ints) {
System.out.print(anInt+" ");
}
System.out.println();
}
StringBuilder与StringBuffer
StringBuffer 线程安全
StringBuilder 非线程安全
StringBuilder sb = new StringBuilder(10);
sb.append("Runoob.."); sb.insert(8, "Java");
sb.delete(5,8);
//StringBuffer的应用
StringBuffer sBuffer = new StringBuffer("菜鸟教程官网:"); sBuffer.append("www");