在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待转换的字符串