Java 字符串

字符串是编程中经常要用到的数据结构,它是字符的序列,从某种程度上来说类似于字符的数组。
实际上,在C语言中,字符串就是用字符数组来实现的。
而在面向对象的Java语言中,字符串是用来实现的。

创建字符串

在JAVA语言中,字符串数据实际上由String类所实现的。 Java字符串类分为两类:一类是在程序中不会被改变长度的不变字符串;二类是在程序中会被改变长度的可变字符串。Java环境为了存储和维护这两类字符串提供了 String 和StringBuffer两个类。
① String str=new(“This is a String”);
② 或者 String str=“This is a String”;

public class StringDemo{ 
	public static void main(String args[]){ 
		char[] helloArray = { 'U', 'E', 'S', 'T', 'C'}; 
		String helloString = new String(helloArray);  
		System.out.println( helloString ); 
	} 
}
public class StringDemo { 
	public static void main(String args[]) { 
		String site = "www.uestc.edu.cn"; 
		int len = site.length(); 
		System.out.println("电子科大域名长度 : " + len ); 
	} 
}

创建格式化字符串

Java输出格式化数字可以使用 printf() 和 format() 方法。
String 类使用静态方法 format() 返回一个String 对象而不是 PrintStream 对象。 String 类的静态方法 format() 能用来创建可复用的格式化字符串,而不仅仅是用于一次打印输出。
System.out.printf(“浮点型变量的值为 " +”%f, 整型变量的值为 " + " %d, 字符串变量的值为 " +“is %s”, floatVar, intVar, stringVar);

String fs = String.format("浮点型变量的值为 " + "%f, 整型变量的值为 " + " %d, 字符串变量的值为 " + " %s", floatVar, intVar, stringVar);

字符串可以通过“+”连接,基本数据类型与字符串进行“+” 操作,一般也会自动转换为字符串。

public class Demo { 
	public static void main(String[] args){ 
		String stuName = "小明"; 
		int stuAge = 17; 
		float stuScore = 92.5f; 
		String info = stuName + "的年龄是 " + stuAge + ",成绩是 " + stuScore; System.out.println(info); 
	} 
}

字符串相关方法

通过调用length()方法得到String的长度。例如:
① String str=“ThisisaString”;
② int len =str.length();

如果想确定字符串中指定字符或子字符串在给定字符串的位置,可用**indexOf(subString[, startIndex])和lastIndexOf(subString)**方法。例如:
① String str=“ThisisaString”;
② int index1 =str.indexOf(“i”); //index=2
③ int index2=str.indexOf(“i”,index1+1); //index2=4
④ int index3=str.lastIndexOf(“i”); //index3=10
⑤ int index4=str.indexOf(“String”); //index4=7

String类的equals()方法用来确定两个字符串是否相等。例如:
① String str=“This is a String”;
② Boolean result=str.equals(“This is another String”);

方法charAt()用以得到指定位置的字符。例如:
① String str=“Thisis a String”;
② char chr=str.charAt(3); //chr=s

方法getChars()用以得到字符串的一部分字符串。例如:
① public void getChars(int srcBegin,intsrcEnd,char[]dst,intdstBegin)
② String str=“ThisisaString”;
③ Char chr =new char[10];
④ Str.getChars(5,12,chr,0);
⑤ System.out.println(new String(chr));
输出:saStrin

public String substring(int beginIndex, int endIndex) 求子字符串
第一个int为开始的索引,对应String数字中的开始位置,
第二个是截止的索引位置,对应String中的结束位置
取得的字符串长度为:endIndex - beginIndex;
从beginIndex开始取,到endIndex结束,从0开始数,其中不包括 endIndex位置的字符
① String str=“ThisisaString”;
② String str1=str.substring(1,4);
③ System.out.println(str1); 输出:his

replace()方法可以将字符串中的一个字符替换为另一个字符
① String str=“ThisisaString”;
② String str1=str.replace(‘T’,‘t’);//str1=“thisisaString”

concat()方法可以把两个字符串合并为一个字符串
① String str=“Thisis a String”;
② String str1=str.concat(“Test”); //str1=“Thisis a StringTest”

toUpperCase()toLowerCase()方法分别实现字符串大小写的转换
① String str=“THISISASTRING”;
② String str1=str.toLowerCase(); //str1=“thisisastring”;

trim()方法可以将字符串中开头和结尾处的空格去掉.
① String str=" This is a String ";
② String str1=str.trim(); //str1=“This is a String”

String类提供静态方法valueOf(),它可以将任何类型的数据对象转换为一个字符串。如
System.out.println( String.valueOf(Math.PI) );

split()操作指定字符串作为分隔符,对当前字符串进行分割,分割的结果存个数组中。

import java.util.*;

public class Demo { 
	public static void main(String[] args){ 
		String str = “UESTC_is_good"; 
		String strArr[] = str.split("_"); 
		System.out.println(strArr[0]); 
		System.out.println(strArr[1]); 
		System.out.println(strArr[2]);
		System.out.println(Arrays.toString(strArr));
	}
}

在这里插入图片描述

修改可变字符串

StringBuffer类为可变字符串的修改提供了3种方法,在字符串中间插入
和改变某个位置所在的字符。
① 在字符串后面追加:用append()方法将各种对象加入到字符串中。
② 在字符串中间插入:用insert()方法
改变某个位置所在的字符,用**setCharAt()**方法。

StringBuffer str=new StringBuffer("Thisis a String");
str.insert(9,"test ");
System.out.println(str.toString());  //输出: Thisis a test String
StringBuffer sb =new StringBuffer("aaaaaa");
sb.setCharAt(2,‘b’);// sb 的值 aabaaa
System.out.println(sb);
public class TestString{
public static void main(String args[]){
	StringBuffer sBuffer = new StringBuffer(“电子科技大学官网:");
	sBuffer.append("www");
	sBuffer.append(".uestc");
	sBuffer.append(".edu");
	sBuffer.append(".cn");
	System.out.println(sBuffer);  
	}
}

StringBuffer与String效率比较

public class StringDemo { 
	public static void main(String[] args){ 
		String fragment = "abcdefghijklmnopqrstuvwxyz"; 
		int times = 10000; 
		long timeStart1 = System.currentTimeMillis(); 
		String str1 = " " ;  // 测试String对象 
		for (int i=0; i<times; i++) { 
			str1 += fragment; 
		} 
		long timeEnd1 = System.currentTimeMillis(); 
		System.out.println("String: " + (timeEnd1 - timeStart1) + "ms"); 
		long timeStart2 = System.currentTimeMillis(); 
		StringBuffer str2 = new StringBuffer(); // 测试StringBuffer 
		for (int i=0; i<times; i++) { 
			str2.append(fragment); 
		} 
		long timeEnd2 = System.currentTimeMillis(); 
		System.out.println("StringBuffer: " + (timeEnd2 - timeStart2) + "ms");   
	} 
}

Stringbuffer >> String

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值