在Java中,處理字符串、文本的時候,一般常用一下三種類:
String、StringBuffer、StringBuilder
參考:https://blog.csdn.net/fyp19980304/article/details/79802590
三者分別有各自適用的場合。
String:適用於少量的字符串操作的情況。
StringBuilder:適用於單線程下在字符緩衝區進行大量操作的情況。
StringBuffer:適用多線程下在字符緩衝區進行大量操作的情況。
String用法:
1、將數組中元素以字符串形式輸出
數組可以使byte類型的,也可以是char類型的(強制轉換爲字符串)。舉例如下:
public class str
{
public static void main(String[] args)
{
byte[] b={97,98,99};
String str=new String(b);
System.out.println(str);
}
輸出結果:abc;
public class strTest
{
public static void main(String[] args)
{
char[] c={'H','e','l','l','o'};
String str=new String(c);
System.out.println(str);
}
輸出結果:Hello;
當然,也可以把數組中的特定元素片段轉換成字符串輸出。
public class strTest
{
public static void main(String[] args)
{
byte[] b={97,98,99,100,101,102};
String str=new String(b,3,2);
System.out.println(str);
}
輸出:de;
從數組元素b[3]開始(包括b[3]在內)的連續兩個元素以字符串形式輸出。
2、字符串中的一些常用函數:連接concat()、提取substring()、charAt()、length()、equals()、equalsIgnoreCase()等等。
String str1="you";
String str2=" welcome";
System.out.println(str1.concat(str2));
輸出結果:you welcome;
String str="we are students and he is a techer";
System.out.println(str.substring(2,10));
輸出結果: are stu ;
從str[2]開始,到str[9]結束。
substring() 方法用於提取字符串中介於兩個指定下標之間的字符。
stringObject.substring(start,stop)
String str="we are students and he is a worker";
System.out.println(str.charAt(1));
輸出結果:e;
charAt(int index)方法是一個能夠用來檢索特定索引下的字符的String實例的方法.
charAt()方法返回指定索引位置的char值。索引範圍爲0~length()-1.
如: str.charAt(0)檢索str中的第一個字符,str.charAt(str.length()-1)檢索最後一個字符.
String str="we are";
System.out.println(str.length());
輸出結果:6;
比較兩個字符串是否相同用equals():
public class test {
public static void main(String[] args) {
String str1="we are students and he is a worker";
String str2="we are students and he is a worker";
System.out.println(str1.equals(str2));
}
}
輸出結果:true;
3、字符串的一些檢索查找字符的函數
public class test {
public static void main(String[] args) {
String str="我們一起數到6吧!";
System.out.println(str.indexOf("一"));
System.out.println(str.indexOf("6"));
System.out.println(str.startsWith("我"));
System.out.println(str.endsWith("!"));
}
}
輸出結果:
2
6
true
true
補充:Java如何遍歷字符串:
String s="abcde";
for(int i=0;i<s.length();i++)
{
char c=s.charAt(i);
System.out.print(c+" ");//輸出a b c d e,獲取字符串
}
String[] s1={"a","b","c","d","e"};
for(int i=0;i<s1.length;i++)
{
System.out.print(s1[i]+" ");//輸出a b c d e,獲取字符串數組
}
Java如何把String字符串轉換爲數字?
1、轉換爲浮點型:
使用Double或者Float的parseDouble或者parseFloat方法進行轉換
String s = "123.456 ";
double d = Double.parseDouble(s);
float f = Float.parseFloat(s);
轉換爲整型:
使用Integer的parseInt方法進行轉換。
int i = Integer.parseInt(str);//str待轉換的字符串