Java学习记录(二)string类的基本用法

在java中的java.lang中有一个常用的string类,本文将介绍其某些基本用法

1. 关于string类

string是Java中的常用名词,在Java中tring类是不可变的,对String类的任何改变,都是返回一个新的String类对象。

2. 基本用法

1) 字符串的声明

java中字符串用 " " 括起来 , 字符串的声明:String + 字符串name;
声明及初始化:**

String str="hellojava";

2) 创建字符串

 String str=new String("hello");

3 ) 连接字符串

public String concat(String str)//将参数中的字符串str连接到当前字符串的后面,效果等价于"+"。

	String str = "hello".concat("java"); //相当于String str = "hello"+"java";
	System.out.println(str);
	输出结果:hellojava

4) 获取字符串长度

public  class  test {
 	public static void main(String[] args) {
 		String s1="hello";
 		String s2="java";		
 		int size1=s1.length();		
 		int size2=s2.length();		
 		System.out.println(size1);		
 		System.out.println(size2);	
 		//输出结果:5  4
 	}
 }

5) 字符串的查找
public int indexOf(int ch/String str)//用于查找当前字符串中字符或子串,返回字符或子串在当前字符串中从左边起首次出现的位置,若没有出现则返回-1。

public class test {	
	public static void main(String[] args) {		
		String s1="hello";		
		String s2="java";		
		int size01=s1.indexOf("l");		
		int size02=s2.indexOf("c");					
		System.out.println(size01);		
		System.out.println(size02);
		//输出结果:2 -1 		
		}
	}

6) 获取字符串子串
用String类的substring方法可以提取字符串中的子串

 public class test {	
 	public static void main(String[] args) {		
 		String s1="hello";		
 		String s2="java";		
 		String str=s1.substring(3);		
 		String str1=s2.substring(0,2);		
 		String str2=s2.substring(1,3);		
 		System.out.println(str);
 		System.out.println(str1);		
 		System.out.println(str2);			
 		}
 	}
 	//输出结果: lo jav ave

7) 字符串比较
1)public int compareTo(String anotherString)//该方法是对字符串内容按字典顺序进行大小比较,通过返回的整数值指明当前字符串与参数字符串的大小关系。若当前对象比参数大则返回正整数,反之返回负整数,相等返回0。
2)public int compareToIgnore(String anotherString)//与compareTo方法相似,但忽略大小写。
3)public boolean equals(Object anotherObject)//比较当前字符串和参数字符串,在两个字符串相等的时候返回true,否则返回false。
4)public boolean equalsIgnoreCase(String anotherString)//与equals方法相似,但忽略大小写。

String str1 = new String("abc");
String str2 = new String("ABC");
int a = str1.compareTo(str2);//a>0
int b = str1.compareTo(str2);//b=0
boolean c = str1.equals(str2);//c=false
boolean d = str1.equalsIgnoreCase(str2);//d=true

8) 字符串的替换
replace()方法将指定的字符或字符串换成新的字符或字符串

public class test {	
	public static void main(String[] args) {		
		String str=" i_love_poland";		
		String newstr=str.replaceAll("i", "I");		
		System.out.println(newstr);
	}
}
//输出结果 : I_love_poland 

发布了5 篇原创文章 · 获赞 3 · 访问量 495

猜你喜欢

转载自blog.csdn.net/qq_40552794/article/details/82890917
今日推荐