Java基础(十五)

String类的常用方法:

1:JavaDoc简介

以后的开发过程中会大量使用Java的API文档(JavaDoc);地址:
https://docs.oracle.com/javase/9/docs/api/overview-summary.html

在这里插入图片描述

在JDK1.9之前,所有的Java中的常用类库都会在JVM启动的时候进行全部的加载,这样实际上性能会有所下降;
在JDK1.9开始提供有模块化设计,将一些程序类放在了不同的模块里面。

点击这里:在这里插入图片描述
在模块之中会包含大量的程序开发包。
在这里插入图片描述

打开String类的相关定义,打开java.lang这个包,赵到String这个类

在这里插入图片描述

在这里插入图片描述

注意:看原版英文的,不要看翻译版本

2:字符串与字符数组

在JDK1.9之前,所有的String都利用了字符数组实现了包装的处理,所以在String类里面提供转换处理的方法,有构造方法和普通方法两类;

构造方法
public String​(char[] value)	
Allocates a new String so that it represents the sequence of characters currently contained in the character array argument.
将传入的全部字符数组变为字符串
构造方法
public String​(char[] value, int offset, int count)	
Allocates a new String that contains characters from a subarray of the character array argument.
将部分字符数组变为字符串
普通方法
public char	charAt​(int index)	
Returns the char value at the specified index.
获取指定索引位置的字符
普通方法
char[]	toCharArray​()	
Converts this string to a new character array.
将字符串中的数据以字符数组的形式返回
public class Test
{
	public static void main(String args[]) {
		String str = "www.mldn.cn" ;
		char c = str.charAt(5) ;
		System.out.println(c) ;
	}
}//输出结果为  l
//程序中的索引下标都是从0开始的。
//实现字符串与字符数组的转换
public class Test {
	public static void main(String args[]) {
		String str = "helloworld" ;
		char [] result = str.toCharArray() ; // 将字符串变为字符数组
		for (int x = 0 ;x < result.length ; x ++) {
			result[x] -= 32 ;	// 编码减少32
		}
		// 将处理后的字符数组交给String变为字符串
		String newStr = new String(result) ;
		System.out.println(newStr) ;
		System.out.println(new String(result,0,5)) ;
	}
}//输出结果:HELLOWORLD
//HELLO

案例:做一个验证功能,判断某一个字符串中的数据是否全部由数字组成,采用如下思路:

如果想要判断字符串中的每一位最好的做法是将字符串变为字符数组;
可以判断每一个字符是否在数字的范围之内(‘0’~‘9’);
如果有一位不是数字返回false;

public class Test {
	public static void main(String args[]) {
		String str = "helloworld" ;
		System.out.println(isNumber(str) ? "由数字所组成" : "不是由数字所组成") ;
		System.out.println(isNumber("123") ? "由数字所组成" : "不是由数字所组成") ;
	}
	// 该方法主要是判断字符串是否由数字所组成
	public static boolean isNumber(String str) {
		char [] result = str.toCharArray() ; // 将字符串变为字符数组
		for (int x = 0 ; x < result.length ; x ++) {	// 依次判断
			if (result[x] < '0' || result[x] > '9') {
				return false ;	// 后面不再判断
			}
		}
		return true ;
	}
}
//不是由数字所组成
//由数字所组成

注意:实际开发中处理中文的时候往往使用char类型,因为其可以包含中文数据。

3:字符串与字节数组

字符串与字节数组之间也可以实现转换操作,当进行了字符串与字节转换时,主要目的是为了进行二进制的传输,或者进行编码转换。

构造方法
public String​(byte[] bytes)	
Constructs a new String by decoding the specified array of bytes using the platform's default charset.
//将全部的字符数组变成字符串
构造方法
public String​(byte[] bytes, int offset, int length)	
Constructs a new String by decoding the specified subarray of bytes using the platform's default charset.
//将部分字节数组变成字符串
普通方法
public byte[]	getBytes​()	
Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.
//将字符串变成字节数组
普通方法
public byte[] getBytes​(String charsetName)
                throws UnsupportedEncodingException
Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array.
//编码转换。
//案例1:字节与字符串的转换
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,0,5)) ;
	}
}
//字节本身是有长度限制的,一个字节保存范围是:-128~127之间。

4:字符串比较

public boolean	equals​(Object anObject)	
Compares this string to the specified object.
//区分大小写的相等判断
public boolean	equalsIgnoreCase​(String anotherString)	
Compares this String to another String, ignoring case considerations.
//不区分大小比较
public int	compareTo​(String anotherString)	
Compares two strings lexicographically.
//进行字符串大小的比较,该方法返回一个int数据:大于(>0),小于(<0),等于(=0)。
public int	compareToIgnoreCase​(String str)	
Compares two strings lexicographically, ignoring case differences.
//不区分大小写及逆行字符串大小比较。
//案例1:区分大小写比较
public class StringDemo {
	public static void main(String args[]) {
		String strA = "mldn" ;
		String strB = "MLDN" ;
		System.out.println(strA.equals(strB)) ;
	}
}
//案例2:不区分大小写比较
public class StringDemo {
	public static void main(String args[]) {
		String strA = "mldn" ;
		String strB = "MLDN" ;
		System.out.println(strA.equalsIgnoreCase(strB)) ;
	}
}
//案例3:进行大小比较
public class StringDemo {
	public static void main(String args[]) {
		String strA = "mldn" ;
		String strB = "mldN" ;
		System.out.println(strA.compareTo(strB)) ;	// 32
		System.out.println(strB.compareTo(strA)) ;	// -32
		System.out.println("Hello".compareTo("Hello")) ;	// 0
	}
}
//案例4:
public class StringDemo {
	public static void main(String args[]) {
		String strA = "mldn" ;
		String strB = "mldN" ;
		System.out.println(strA.compareToIgnoreCase(strB)) ;	// 0
	}
}
//由于此时的内容一样,所以在不计较大小写的情况下,两者的比较结果是相同的。

5:字符串查找

从一个完整字符串之中查找子字符串的存在就属于字符串查找操作,String类中有如下几个查找方法:

//方法1:此方法是JDK1.5之后追加的功能
public boolean	contains​(CharSequence/String s)	
Returns true if and only if this string contains the specified sequence of char values.
//判断子字符串是否中存在
//方法2
public int	indexOf​(String str)	
Returns the index within this string of the first occurrence of the specified substring.
//从头查找指定字符串的位置,找不到返回-1
//方法3
public int	indexOf​(String str, int fromIndex)	
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
//从指定位置查找指定字符串的位置
//方法4:
public int	lastIndexOf​(String str)	
Returns the index within this string of the last occurrence of the specified substring.
//由后向前查找指定字符串的位置
//方法5
public int	lastIndexOf​(String str, int fromIndex)	
Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.
//从指定位置由后往前查找指定字符串的位置
//方法6
public boolean	startsWith​(String prefix)	
Tests if this string starts with the specified prefix.
//判断是否以指定的字符串开头
//方法7
public boolean	startsWith​(String prefix, int toffset)	
Tests if the substring of this string beginning at the specified index starts with the specified prefix.
//由指定位置判断是否以指定的字符串开头
//方法8
public boolean	endsWith​(String suffix)	
Tests if this string ends with the specified suffix.
//判断是否以直指定的字符串结尾。
//案例1:判断子字符串是否存在
public class StringDemo {
	public static void main(String args[]) {
		String str = "www.mldn.cn" ;
		System.out.println(str.contains("mldn")) ;	// true
		System.out.println(str.contains("hello")) ;	// false
	}
}
//案例2:判断字符串是否存在
public class StringDemo {
	public static void main(String args[]) {
		String str = "www.mldn.cn" ;
		System.out.println(str.indexOf("mldn")) ;
		System.out.println(str.indexOf("hello")) ;	// -1
		if (str.indexOf("mldn") != -1) {
			System.out.println("数据存在。") ;
		}
	}
}
//indexOf()是为了进行字符串位置的查询,可以利用此方法进行一些索引的确定,从前往后的
//案例3:使用lastIndexOf()从后往前查找
public class StringDemo {
	public static void main(String args[]) {
		String str = "www.mldn.cn" ;
		System.out.println(str.lastIndexOf(".")) ;
	}
}
//案例4:判断是否以指定的字符串开头或结尾
public class Demo{
	public static void main(String args[]){
		String str = "**@@##";
		System.out.println(str.startsWith("**"));
		System.out.println(str.startsWith("@@",2));
		System.out.println(str.ednsWith("##"));
	}
}


6:字符串替换:

所谓的字符串替换指的是可以通过一个指定的内容进行指定字符串的替换显示。

//方法1
public String	replaceAll​(String regex, String replacement)	
Replaces each substring of this string that matches the given regular expression with the given replacement.
//全部替换
//方法2
public String	replaceFirst​(String regex, String replacement)	
Replaces the first substring of this string that matches the given regular expression with the given replacement.
//替换首个
//案例1:
public class StringDemo {
	public static void main(String args[]) {
		String str = "helloworld" ;
		System.out.println(str.replaceAll("l","X")) ;
		System.out.println(str.replaceFirst("l","X")) ;
	}
}

7:字符串拆分

字符串的拆分主要是可以根据一个指定的字符串或者是一些表达式实现拆分,拆分完成的数据以字符串数组的形式返回。

//方法1
public String[]	split​(String regex)	
Splits this string around matches of the given regular expression.
//按照指定的字符串全部拆分
//方法2
public String[]	split​(String regex, int limit)	
Splits this string around matches of the given regular expression.
//按照指定的字符串拆分为指定个数,后面不拆了。
//案例1:全部拆分
public class StringDemo {
	public static void main(String args[]) {
		String str = "hello world hello mldn" ;
		String result [] = str.split(" ") ; // 空格拆分
		for (int x = 0 ; x < result.length ; x ++) {
			System.out.println(result[x]) ;
		}
	}
}
//案例2:拆分指定个数
public class StringDemo {
	public static void main(String args[]) {
		String str = "hello world hello mldn" ;
		String result [] = str.split(" ",2) ; // 空格拆分
		for (int x = 0 ; x < result.length ; x ++) {
			System.out.println(result[x]) ;
		}
	}
}
//案例3:拆分的时候可能遇到拆分不了的情况,使用“\\”进行转义
public class StringDemo {
	public static void main(String args[]) {
		String str = "192.168.1.2" ;
		String result [] = str.split("\\.") ; // 空格拆分
		for (int x = 0 ; x < result.length ; x ++) {
			System.out.println(result[x]) ;
		}
	}
}

8:字符串截取

//方法1
public String	substring​(int beginIndex)	
Returns a string that is a substring of this string.
//从指定索引截取到结尾
//方法2
String	substring​(int beginIndex, int endIndex)	
Returns a string that is a substring of this string.
//截取指定索引范围内的子字符串
//案例1
public class StringDemo {
	public static void main(String args[]) {
		String str = "www.mldn.cn" ;
		System.out.println(str.substring(4)) ;
		System.out.println(str.substring(4,8)) ;
	}
}
//案例2:截取出字符串中的姓名
public class StringDemo {
	public static void main(String args[]) {
		// 字符串结构:“用户id-photo-姓名.后缀”
		String str = "mldn-photo-张三.jpg" ;
		int beginIndex = str.indexOf("-",str.indexOf("photo")) + 1;
		int endIndex = str.lastIndexOf(".") ;
		System.out.println(str.substring(beginIndex,endIndex)) ;
	}
}
//在实际开发中,通过这种计算来确定索引的位置非常常见。

9:格式化字符串

从JDK1.5开始为了吸引更多的传统的开发人员。Java提供了格式化数据的处理操作,类似于语言的格式化输出语句,可以利用占位符实现数据的输出,常用的:

字符串(%s),字符(%c),整数(%d),小数(%f)等。

方法1
public static String	format​(String format, Object... args《各种类型》)	
Returns a formatted string using the specified format string and arguments.
//根据指定结构进行文本格式化显示。
案例1:
public class StringDemo {
	public static void main(String args[]) {
		String name = "张三" ;
		int age = 18 ;
		double score = 98.765321 ;
		String str = String.format("姓名:%s、年龄:%d、成绩:%5.2f。",name,age,score) ;
		System.out.println(str) ;
	}
}

10:其他方法

//方法1:字符串的连接
public String	concat​(String str)	
Concatenates the specified string to the end of this string.

//方法2:字符串入池
public String	intern​()	
Returns a canonical representation for the string object.
//方法3:判断是否为空字符串
public boolean	isEmpty​()	
Returns true if, and only if, length() is 0.
//方法4:计算字符串的长度
public int	length​()	
Returns the length of this string.
//方法5:去除左右的空格信息
public String	trim​()	
Returns a string whose value is this string, with any leading and trailing whitespace removed.
//方法6:转大写
public String	toUpperCase​()	
Converts all of the characters in this String to upper case using the rules of the default locale.
//方法7:转小写
public String	toLowerCase​()	
Converts all of the characters in this String to lower case using the rules of the given Locale.
//案例1:观察字符串连接
public class StringDemo {
	public static void main(String args[]) {
		String strA = "www.mldn.cn" ;
		String strB = "www.".concat("mldn").concat(".cn") ;
		System.out.println(strB) ;
		System.out.println(strA == strB) ;	// false
	}
}
//虽然内容相同,但是返回了false,证明次操作没有实现静态的定义
//案例2:判断空字符串

//字符串定义的时候   “”  和 null  不是一个概念,前者表实例化了对象,后者表示没有实例化对象,而isEmpty()是判断字符串的内容,所以一定要在有实例化对象的时候进行调用。

public class StringDemo {
	public static void main(String args[]) {
		String str = "" ;
		System.out.println(str.isEmpty()) ;	// true
		System.out.println("mldn".isEmpty()) ;	// false
	}
}
//案例3:观察length()和trim()
public class StringDemo {
	public static void main(String args[]) {
		String str = "   Hello World   " ;
		System.out.println(str.length()) ;	// 长度
		String trimStr = str.trim() ;
		System.out.println(str) ;
		System.out.println(trimStr) ;
		System.out.println(trimStr.length()) ;
	}
}
//在进行一些数据输入的时候(用户名和密码),很难保证输入的时候没有空格,那么必须对输入的数据进行处理,使用trim();
案例4:大小写转换
public class StringDemo {
	public static void main(String args[]) {
		String str = "Hello World !!!" ;
		System.out.println(str.toUpperCase()) ;
		System.out.println(str.toLowerCase()) ;
	}
}
//这样的方式可以节省开发成本
**案例5:自定义一个实现首字母大写的方法**
class StringUtil {
	public static String initcap(String str) {
		if (str == null || "".equals(str)) {
			return str ;	// 原样返回
		}
		if (str.length() == 1) {
			return str.toUpperCase() ;
		}
		return str.substring(0,1).toUpperCase() + str.substring(1) ;
	}
}
//日后实际开发中必定要用到的程序

总结:熟练掌握!灵活应用!做一个有情怀的coder!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值