String类常用方法

String在所有的项目开发中都一定要使用到,那么在String类里面提供了一系列的功能操作方法,本次学习其中大部分的操作方法,而对于有一些操作,需要等待全部的知识掌握之后才可以进行后续的学习。

对于系统类的方法,一定要去查询文档,一些不常用的方法允许不知道,但是一定要会查。而对于String类的一些方法,由于使用的情况比较多,为了方便开发必须背。

对于每一个API文档的内容而言,都由以下几个部分组成:

· 类的定义以及相关的继承结构;

· 类的一些简短的说明;

· 类中的成员组成;

· 类中所提供的构造方法;

· 类中所提供的普通方法;

· 成员、构造方法、普通方法的详细说明。


一、字符与字符串

很多的语言之中都是利用字符数组的概念来描述字符串的信息,这一点在String类的方法上也都有所提供。

No

方法名称

类型

功能

1

public String(char[] value)

构造

将字符数组变为String类对象

2

public String(char[] value,int offset,int count)

构造

将部分字符数组变为String类对象

3

public char charAt(int index)

普通

返回指定索引对应的字符信息

4

public char[] toCharArray()

普通

将字符串以字符数组的形式返回

范例:取出指定索引的字符

public class StringDemo {
	public static void main(String[] args) {
		String str = "hello";
		char c = str.charAt(0);
		System.out.println(c);
	}
}

程序之中字符串的下标都是从0开始的。

范例:字符数组与字符串的转换

public class StringDemo {
	public static void main(String[] args) {
		String str = "hello";
		char[] data = str.toCharArray();// 将字符串变为字符数组
		for (int x = 0; x < data.length; x++) {
			System.out.println(data[x] + "、");
		}
	}
}

范例:将字符串转大写

public class StringDemo {
	public static void main(String[] args) {
		String str = "hello";
		char[] data = str.toCharArray();// 将字符串变为字符数组
		for (int x = 0; x < data.length; x++) {
			data[x] -= 32;
			// 字符遇到与数字相加减,字符先变为数字相加减,由于最后的类型是char,所以输出的值还是char
		}
		System.out.println(new String(data));// 将全部字符数组变为String
		System.out.println(new String(data, 1, 2));
		// 将部分字符数组变成变成String类对象
		// 1是从索引为1的字符开始,2是指从索引字符开始解释两个字符,即长度
	}
}

范例:给定一个字符串,要求判断其是否由数字组成

思路:如果整个字符串要判断是不是数字无法实现,但是可以将字符串变为字符数组,而后判断每一个字符的内容是否是数字,如果该字符的范围在(‘0’ ~‘9’)指定的范畴之内,那么就是数字。

public class StringDemo {
	public static void main(String[] args) {
		String str = "123423432";
		if (isNumber(str)) {
			System.out.println("字符串由数字组成");
		} else {
			System.out.println("字符串由非数字组成");
		}
	}

	// 判断字符串是否有数字组成,如果是返回true,否则返回false
	public static boolean isNumber(String temp) {
		// 将字符串变为字符数组,取出每一个字符来判断
		char[] data = temp.toCharArray();
		for (int x = 0; x < data.length; x++) {
			if (data[x] > '9' || data[x] < '0') {// 有一个不是数字则直接返回false
				return false;
			}
		}
		return true; // 全部验证通过返回true
	}
}

如果写的某一个方法返回的内容时boolean,那么习惯性的做法是将其以“isXxx”进行命名。


二、字节与字符串

字节使用byte描述,使用字节一般主要用于数据的传输或者进行编码转换的时候使用,而在String类里面就提供有将字符串变为字节数组的操作,目的就是为了传输以及编码转换。

No

方法名称

类型

功能

1

public String(byte[] bytes)

构造

将全部的字节数组变为字符串

2

public String(byte[] bytes,int offset,int length)

构造

将部分字节数组变为字符串

3

public byte[] getBytes()

普通

将字符串变为字节数组

4

public byte[] getBytes(String charsetName)throws UnsupportedEncodingException

普通

进行编码转换

范例:观察字符串与字节数组的转换

public class StringDemo {
	public static void main(String[] args) {
		String str = "helloworld";
		byte[] data = str.getBytes();// 将字符串变为字节数组
		for (int x = 0; x < data.length; x++) {
			data[x] -= 32;// 将小写字母变为大写形式
		}
		System.out.println(new String(data));// 全部转换
		System.out.println(new String(data, 5, 5));// 部分转换
	}
}

因为现在操作的是英文字母,所以感觉与字符类似。

在以后IO操作中会牵扯到这种字节数组的操作,在后续开发之中会逐步接触到乱码的处理问题。


三、字符串比较

如果要进行字符串内容相等的判断使用equals(),但是在String类里面定义的比较判断不只这一个。

No

方法名称

类型

功能

1

public boolean equals(String anObject)

普通

进行相等的判断,它区分大小写

2

public boolean equalsIngnoreCase(String anotherString)

普通

进行相等的判断,不区分大小写

3

public int compareTo(String anotherString)

普通

判断两个字符串的大小(按照字符编码比较),此方法返回值有如下三种结果:①“=0”表示要比较的两个字符串内容相等②“>0”表示大于的结果③“<0”表示小于的结果

范例:相等判断

public class StringDemo {
	public static void main(String[] args) {
		String stra = "Hello";
		String strb = "HELLO";
		System.out.println(stra.equals(strb));// false
		System.out.println(stra.equalsIgnoreCase(strb));// true
	}
}

范例:观察compareTo()方法

public class StringDemo {
	public static void main(String[] args) {
		String stra = "Hello";
		String strb = "HELLO";
		System.out.println(stra.compareTo(strb));
		// 可以利用大小等于0的方式来判断大小
		if (stra.compareTo(strb) > 0) {
			System.out.println("大于");
		}
	}
}

只有String类的对象才具有大小的关系判断。


四、字符串查找

从一个完整的字符串之中要判断某一个子字符串是否存在,这一功能可以使用如下方法完成:

No

方法名称

类型

功能

1

public boolean contains(String s)

普通

判断指定的内容是否存在

2

public int indexOf(String str)

普通

由前向后查找指定字符串的位置,如果查找到了则返回第一个字母位置的索引,如果找不到则返回-1

3

public int indexOf(String str,int fromIndex)

普通

由指定位置从前向后查找指定字符串的位置,找不到则返回-1

4

public int lastIndexOf(String str)

普通

由后向前查找指定字符串的位置,找不到则返回-1

5

public int lastIndexOf(String str,int fromIndex)

普通

由指定位置从后向前查找指定字符串的位置,找不到则返回-1

6

public boolean startsWith(String perfix)

普通

判断是否以指定的字符串开头

7

public boolean startsWith(String perfix,int toffset)

普通

从指定位置开始判断是否以指定的字符串开头

8

Public boolean endsWith(String suffix)

普通

判断是否以指定的字符串结尾

范例:使用indexOf()等功能查找

public class StringDemo {
	public static void main(String[] args) {
		String str = "helloworld";
		// 返回满足条件单词的第一个字母索引
		System.out.println(str.indexOf("world"));
		// 返回的是第一个查找到的
		System.out.println(str.indexOf("l"));
		System.out.println(str.indexOf("l", 5));
		// 从后开始查找
		System.out.println(str.lastIndexOf("l"));
	}
}

以上的过程都只是返回了一个位置,但是在一些程序之中需要告诉用户的是有没有的结果,最早的做法是判断查询结果是否是“-1”来实现的。

public class StringDemo {
	public static void main(String[] args) {
		String str = "helloworld";
		if (str.indexOf("world") != -1) {
			System.out.println("可以查询到数据");
		}
	}
}

但是从JDK1.5开始出现了contains()方法,这个方法可以直接返回boolean。

public class StringDemo {
	public static void main(String[] args) {
		String str = "helloworld";
		if (str.contains("world")) {
			System.out.println("可以查询到数据");
		}
	}
}

使用contains()更加简单,并且在整个Java里面,contains()已经成为查询的代名词。

范例:开头或结尾判断

public class StringDemo {
	public static void main(String[] args) {
		String str = "##@@helloworld**";
		System.out.println(str.startsWith("##"));
		System.out.println(str.startsWith("@@", 2));
		System.out.println(str.endsWith("**"));
	}
}

这些开头和结尾的判断往往可以作为一些标记在程序中出现。


五、字符串替换

指的是使用一个新的字符串替换一个旧的字符串数据,支持的方法有如下几个:

No

方法名称

类型

功能

1

public String replaceAll(String regex,String replacement)

普通

用新的内容替换掉全部旧的内容

2

public String replaceFirst(String regex,String replacement)

普通

替换掉首个满足条件的内容

范例:观察替换的结果

public class StringDemo {
	public static void main(String[] args) {
		String str = "helloworld";
		String resultA = str.replaceAll("l", "_");
		String resultB = str.replaceFirst("l", "_");
		System.out.println(resultA);
		System.out.println(resultB);
	}
}

对于替换的操作后续还会有更加完善的讲解。


六、字符串截取

从一个完整的字符串之中可以截取部分的子字符串数据,支持的方法如下:

No

方法名称

类型

功能

1

public String substring(int beginIndex)

普通

从指定索引截取到结尾

2

public String substring(int beginIndex,int endIndex)

普通

截取部分子字符串的数据

范例:验证操作

public class StringDemo {
	public static void main(String[] args) {
		String str = "helloworld";
		String resultA = str.substring(5);
		String resultB = str.substring(0, 5);
		System.out.println(resultA);
		System.out.println(resultB);
	}
}

一定要记住,数据库中的函数由于考虑到有可能是非专业的人员进行使用,所以有些代码尽可能做了一些调整,但是程序是要求严谨性的,所以不可能使用负数作为截取的开始点。


七、字符串拆分

将一个完成的字符串,按照指定的内容拆分为字符串数组(对象数组,String对象),方法如下:

No

方法名称

类型

功能

1

public String[] split(String regex)

普通

按照指定字符串进行全部拆分

2

public String[] split(String regex,int limit)

 普通

按照指定字符串进行部分拆分,最后的数组长度由limit(如果能拆分的结果很多,数组长度才会由limit决定)决定,即:前面拆,后面不拆

范例:进行全部拆分

public class StringDemo {
	public static void main(String[] args) {
		String str = "hello world nihao zhai";
		String result[] = str.split(" ");
		for (int x = 0; x < result.length; x++) {
			System.out.println(result[x]);
		}
	}
}

如果在拆分的时候只是写了一个空字符串(“不是null”),表示按照每一个字符进行拆分。

范例:部分拆分

public class StringDemo {
	public static void main(String[] args) {
		String str = "hello world nihao zhai";
		String result[] = str.split(" ",2);
		for (int x = 0; x < result.length; x++) {
			System.out.println(result[x]);
		}
	}
}

范例:实现IPv4地址拆分

public class StringDemo {
	public static void main(String[] args) {
		String str = "192.168.3.4.";
		String result[] = str.split("\\.");
		for (int x = 0; x < result.length; x++) {
			System.out.println(result[x]);
		}
	}
}

如果是一些敏感字符(正则标记)严格讲是无法拆分的,如果真的遇见了拆分不了的情况,那么使用“\\(就是\)”,进行转义后才可以拆分。

在实际的开发之中,拆分的操作是非常常见的,因为很多的时候会传递一组数据到程序之中进行处理,例如,有如下字符串:“张三:20|李四:21|王五:22|…”(姓名:年龄|姓名:年龄|…),当接收到此数据时必须要对数据进行拆分。

public class StringDemo {
	public static void main(String[] args) {
		String str = "张三:20|李四:21|王五:22";
		String result[] = str.split("\\|");
		for (int x = 0; x < result.length; x++) {
			String temp[] = result[x].split(":");
			System.out.println("姓名:" + temp[0] + ",年龄:" + temp[1]);
		}
	}
}

八、其他操作

以上给出的操作是可以归类的,但是在String里面也有一部分方法是不可以归类的。

No

方法名称

类型

功能

1

public String concat(String str)

普通

字符串的连接,与“+”类似

2

public String toLowerCase()

 普通

转小写

3

public String toUpperCase()

普通

转大写

4

public String trim()

普通

去掉字符串中左右两边的空格,中间空格保留

5

public int length()

普通

取得字符串长度

6

public String intern()

普通

数据入池

7

public boolean isEmpty()

普通

判断是否是空字符串(不是null而是“”,长度是0)

范例:字符串的连接

public class StringDemo {
	public static void main(String[] args) {
		String stra = "hello";
		String strb = "hello " + "world";
		String strc = "hello world";
		System.out.println(stra == strc);//false
		System.out.println(strb == strc);//true
	}
}
public class StringDemo {
	public static void main(String[] args) {
		String stra = "hello";
		String strb = stra + "world";
//String strb = stra.concat("world");等价
		String strc = "hello world";
		System.out.println(stra == strc);//false
		System.out.println(strb == strc);//false
	}
}

范例:转小写与大写

public class StringDemo {
	public static void main(String[] args) {
		String str = "(*(*Hello(*(*";
		System.out.println(str.toLowerCase());
		System.out.println(str.toUpperCase());
	}
}

所有的非字母数据不会进行任何的转换操作。

范例:去掉空格

public class StringDemo {
	public static void main(String[] args) {
		String str = "      Hello world    ";
		System.out.println(str);
		System.out.println(str.trim());
	}
}

一般在用户进行数据输入当然时候,有可能会携带有无用的空格内容,那么接受到这些数据后就要消除掉所有的空格内容。

范例:取得字符串的长度

public class StringDemo {
	public static void main(String[] args) {
		String str = "helloworld";
		System.out.println(str.length());
	}
}

在某些情况下要求用户输入的长度是有限制的,可以利用此方式判断。数组中也有一个length属性,但是调用的形式不同:

· 数组对象.length;

· String对象.length()。

范例:判断是否为空字符串

public class StringDemo {
	public static void main(String[] args) {
		String str = "helloworld";
		System.out.println(str.isEmpty());//false
		System.out.println("".isEmpty());//true
	}
}

如果觉得isEmpty不方便可以使用”“”.equals(str)”。

String虽然提供了大量的支持的方法,但是缺少了一个重要的方法——intitcap()功能,首字母大写,其余字母小写,而这样的功能只能够自己实现。

public class StringDemo {
	public static void main(String[] args) {
		String str = "helloworld";
		System.out.println(initcap(str));
	}

	public static String initcap(String temp) {
		return temp.substring(0, 1).toUpperCase() + temp.substring(1);
	}
}

虽然Java的类库里面没有此功能,但是一些第三方的组件包会提供,例如:apache的commons组件包。

猜你喜欢

转载自blog.csdn.net/L_zhai/article/details/81283988