`

String 类的使用

阅读更多
public class StringTest {
public static void main(String[] args) {
	
	//创建字符串
	String s = "Now";
	String t = s + " is the time.";
	String t1 = s + " " + 23.4; //运算符+会把其他类型的值转换为字符串类型
	
	t1 = String.valueOf('c');      //取得对应每个字符的字符串
	t1 = String.valueOf(42);       //取得字符串类型的整数或一个值
//	t1 = object.toString();
	
	//字符串长度
	int len = t.length();   
	
	String sub = t.substring(4); //返回从位置4开始到结尾的字符串的子串
	
	sub = t.substring(4,6);  //返回位置4和5的字符
	sub = t.substring(0,3);  //返回位置0到2的字符
//	sub = t.substring(x,y);  //返回位置x和y-1之间的字符 
	int numchars = sub.length(); 
	
	char c = t.charAt(2); //取得字符串t的第三个字符w
	char[] ca = t.toCharArray(); //将字符串转换为字符数组
	t.getChars(0, 3, ca, 1); //将字符串t的前三个字符放入ca[1]-ca[3]
	
	String caps = t.toUpperCase();//转换为大写
	String lower = t.toLowerCase();//转换为小写
	
	boolean b1 = t.equals("hello");
	boolean b2 = t.equalsIgnoreCase(caps);
	boolean b3 = t.startsWith("Now");
	boolean b4 = t.endsWith("time");
	
	int r1 = s.compareTo("Pow");
	int r2 = s.compareTo("Now");
	int r3 = s.compareTo("Mow");
	int r4 = s.compareToIgnoreCase("Pow");
	
	int pos = t.indexOf('i'); //第一个"i"的位置:4
	pos = t.indexOf('i',pos+1); //下一个"i"的位置:12
	pos = t.indexOf('i', pos+1); //字符串中不再有"i",返回-1
	pos = t.lastIndexOf('i');//字符串中最后一个"i"的位置:12
	pos = t.lastIndexOf('i', pos -1);//从位置11的字符开始由后往前查找
	
	pos = t.indexOf("is"); //查找子字符串返回4
	pos = t.indexOf("is",pos+1);//只出现一次返回-1
	pos = t.lastIndexOf("the");//由后往前查找字符
	String noun = t.substring(pos + 4);//取出"the"之后的单词
	
	String exclaim = t.replace('.','!');//只能处理字符,不能处理子字符串
	
	String noextraspaces = t.trim();//清楚字符串开头和结尾的空格
	
	String s1 = s.intern();//返回与s相等的字符串s1
	String s2 = "Now";//字符串直接量会自动被保留
	boolean equals = (s1 == s2);//现在可以用==来比较是否相等
}
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics