Java基础之String类 总结

目录

一、与字符串相关的类

 1.1 三者特点

1.2 三者转换

二、String 各种方法

2.1 length 和 concat

2.2 替换 replace 相关

2.3 其它方法

三、StringBuffer 和 StringBuilder

1. StringBuffer

2. StringBuilder

四、判断字符串是否为空的几种方法

五、几种字符转换

5.1 string 与 int 互转

5.2 string 与 double 互转

5.3 string 与 float 互转

5.4 int 与 double 互转

5.5 int 与 float 互转

5.6 double 与 float 互转


一、与字符串相关的类

我们知道与字符串相关的类有三个:

  • String
  • StringBuffer
  • StringBuilder

 1.1 三者特点

【1】String

【2】StringBuffer

可变的字符序列,线程安全的,效率低。

【3】StringBuilder

可变的字符序列,线程不安全的,效率高。

1.2 三者转换

  • String转换为StringBuffer、StringBuilder:** 调用StringBuffer、StringBuilder的构造器。
  • StringBuffer、StringBuilder转换为String:** 调用String的构造器或调用StringBuffer、 StringBuilder的toString方法。
     

二、String 各种方法

2.1 length 和 concat

String s="我是最棒的,I‘m the best。";
System.out.println("长度为:"+s.length());//获取字符串长度
System.out.println(s+"==yes");//字符串连接
System.out.println(s.concat("==yes"));//字符串连接
长度为:19
我是最棒的,I‘m the best。==yes
我是最棒的,I‘m the best。==yes

2.2 替换 replace 相关

【1】public String replace(char searchChar, char newChar):

返回一个新的字符串,它是通过用 newChar 替换此字符串中出现的所有 oldChar 得到的。

public class Main {
    public static void main(String args[]) {
        String Str = new String("Runoob");
        System.out.print("返回值 :" );
        System.out.println(Str.replace('o', 'T'));
        System.out.print("返回值 :" );
        System.out.println(Str.replace('u', 'D'));
    }
}
返回值 :RunTTb
返回值 :RDnoob

【2】String replaceAll(String regex, String replacement):

使用给定的 replacement 替换此字符串所有匹配给定的正则表达式的子字符串。


    public static void main(String args[]) {
        String Str = new String("www.google.com");
        System.out.print("匹配成功返回值 :" );
        System.out.println(Str.replaceAll("(.*)google(.*)", "runoob" ));
        System.out.print("匹配失败返回值 :" );
        System.out.println(Str.replaceAll("(.*)taobao(.*)", "runoob" ));
    }
匹配成功返回值 :runoob
匹配失败返回值 :www.google.com

【3】public String replaceFirst(String regex,String replacement)
replaceFirst() 方法使用给定的参数 replacement 替换字符串第一个匹配给定的正则表达式的子字符串。

public class Test {
    public static void main(String args[]) {
        String Str = new String("hello runoob,I am from runoob。");
        System.out.print("返回值 :" );
        System.out.println(Str.replaceFirst("runoob", "google" ));
        System.out.print("返回值 :" );
        System.out.println(Str.replaceFirst("(.*)runoob(.*)", "google" ));
    }
}
返回值 :hello google,I am from runoob。
返回值 :google

2.3 其它方法

String s1="oh my god! ";
String s2="oh my gosh!";
System.out.println(s1.charAt(6));//返回指定索引的字符(0 ~ length()-1)
System.out.println(s1.startsWith("god!"));//是否以指定前缀开始
System.out.println(s1.startsWith("god!",6));//toffset: 字符开始查找位置 是否以指定前缀开始,
System.out.println(s1.endsWith("god!"));//是否以指定后缀结束
System.out.println(s1.equals(s2));//字符串比较
System.out.println(s1.equalsIgnoreCase(s2));//字符串比较(不考虑大小写)
System.out.println(s1.indexOf("o"));//返回指定字符在字符串中第一次出现处的索引
System.out.println(s1.indexOf("o",7));//从指定索引开始查找,返回指定字符在字符串中第一次出现处的索引
System.out.println(s1.lastIndexOf("o"));//返回指定字符在字符串中最后一次出现处的索引
System.out.println(s1.lastIndexOf("o",7));//从指定索引开始查找,返回指定字符在字符串中最后一次出现处的索引
System.out.println(s1.matches("(.*)my(.*)"));//是否匹配给定的正则表达式
for (String s3:s1.split("y")){
	System.out.println(s3);//把字符串按 regex 拆分成多份
}
System.out.println(s1.substring(5));//返回从指定索引开始的子字符串
System.out.println(s1.substring(5,8));//返回从索引5开始到索引8结束的子字符串,不包括结束索引的字符串
System.out.println(s1.toUpperCase());//全部大写
System.out.println(s1.toLowerCase());//全部小写
System.out.println(s1.trim());//取出前后空白字符
System.out.println(s1.contains("my"));//是否包含指定字符
System.out.println(s1.isEmpty());//判断字符串是否为空
g
false
true
false
false
false
0
7
7
7
true
oh m
 god! 
 god! 
 go
OH MY GOD!
oh my god!
oh my god!
true
false

三、StringBuffer 和 StringBuilder

  • 当对字符串进行修改的时候,需要使用 StringBuffer 和 Stringbuilder 类
  • 和 String 类不同的是,StringBuffer 和 StringBuilder 类的对象能够被多次的修改,并且不产生新的未使用对象。
  • 在使用 StringBuffer 类时,每次都会对 StringBuffer 对象本身进行操作,而不是生成新的对象,所以如果需要对字符串进行修改推荐使用 StringBuffer。
  • StringBuilder 类在 Java 5 中被提出,它和 StringBuffer 之间的最大不同在于 StringBuilder 的方法不是线程安全的(不能同步访问)。
  • 由于 StringBuilder 相较于 StringBuffer 有速度优势,所以多数情况下建议使用 StringBuilder 类。

1. StringBuffer

StringBuffer sBuffer = new StringBuffer("菜鸟教程官网:");
sBuffer.append("www");
sBuffer.append(".runoob");
sBuffer.append(".com");
System.out.println(sBuffer);  
菜鸟教程官网:www.runoob.com
序号方法描述 
1public StringBuffer append(String s) 将指定的字符串追加到此字符序列。
2public StringBuffer reverse() 将此字符序列用其反转形式取代。
3public delete(int start, int end) 移除此序列的子字符串中的字符。
4public insert(int offset, int i) 将 int 参数的字符串表示形式插入此序列中。
5insert(int offset, String str)  将 str 参数的字符串插入此序列中。
6

replace(int start, int end, String str) 使用给定 String 中的字符替换此序列的子字符串中的字符。

 

2. StringBuilder

StringBuilder sb = new StringBuilder(10);
sb.append("Runoob..");
System.out.println(sb);  
sb.append("!");
System.out.println(sb); 
sb.insert(8, "Java");
System.out.println(sb); 
sb.delete(5,8);
System.out.println(sb); 
Runoob..
Runoob..!
Runoob..Java!
RunooJava!

四、判断字符串是否为空的几种方法

【1】最多人使用的一个方法, 直观, 方便, 但效率很低:(后来跟主管讨论说不让使用第一种,原因是==和equals比根本上的不同,一个是比较内存地址一个是比较内容,如果在使用云服务和搭建集群的时候有可能会出问题,虽然性能上会差几ms,但还是让使用第一种,第四种适合简单一般的比较)

if(s == null || "".equals(s));

【2】比较字符串长度, 效率高, 是我知道的最好一个方法:

if(s == null || s.length() == 0);

【3】Java SE 6.0 才开始提供的方法, 效率和方法二几乎相等, 但出于兼容性考虑, 推荐使用方法二.

if(s == null || s.isEmpty());

【4】这是一种比较直观,简便的方法,而且效率也非常的高,与方法二、三的效率差不多:

if (s == null || s == "");

五、几种字符转换

5.1 string 与 int 互转

string --> int

  String number = "-7";
  // result = -7
  int result = Integer.parseInt(number);
  // result2 = -7
  Integer result2 = Integer.valueOf(number);

int --> string

int i=1;
String s = String.valueOf(i);
String s = Integer.toString(i);
String s = “” + i;
 

5.2 string 与 double 互转

string --> double

String toBeDouble =“200.20”;
Double fromString = new Double(toBeDouble);

double -->string

Double toBeString = 400.40;
String fromDouble = "" + toBeString;
 

5.3 string 与 float 互转

string --> float

Float.valueOf(String).floatValue();
Float.parseFloat(String);

float --> string

Float.toString(float);
 

5.4 int 与 double 互转

int--> double

int i = 123;
//1.隐式转换
double d1 = i;
//2.使用Double.valueOf()方法
double d2 = Double.valueOf(i);

double --> int

double doubleValue = 82.14; // 82.14
System.out.println("doubleValue: "+doubleValue);
//typecase double to int
int intValue = (int) doubleValue; // 82
System.out.println("intValue: "+intValue);

 double doubleValue = 82.14; // 82.14
System.out.println("doubleValue: "+doubleValue);
//创建Double wrapper对象
Double doubleValueObject = new Double(doubleValue);
//将case双精度型转换为int
int intValue = doubleValueObject.intValue(); // 82
System.out.println("intValue: "+intValue);
 

5.5 int 与 float 互转

float --> int

float a = 8.61f;
int b = (int)Math.round(a);

int --> float

int a=9;
int b=7;
DecimalFormat df=new DecimalFormat("0.00");
System.out.println(df.format((float)a/b));
System.out.println(df.format(a/(float)b));
System.out.println(df.format((float)a/(float)b));
System.out.println(df.format((float)(a/b)));
 

5.6 double 与 float 互转

String str = "9.2";
Long.parseLong(str ); //异常java.lang.NumberFormatException: For input string: "9.2"
Float.parseFloat(str); //可以
Double.parseDouble(str);//可以

如果有错还请指正,同时也欢迎大家到我的个人博客  ~ 欢迎来到我的小栈 ~  访问留言。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值