java中String实用方法

1、String的创建
// 直接创建
String s1 = "abc";
// new一个
String s2 = new String("abc");

2、字符串比较  “==” 、“equals” 、“equalsIgnoreCase”

(1)“==”

// 等值在引用类型中比较的是地址
// 字符串复值,首先在串池里面找有无相应的字符串,没有,创建一个,有把字符串的地址赋给该变量
// 优点:可以节约空间

String s1 = "abc";
String s2 = "abc";

System.out.println(s1 == s2); //true

String s3 = new String("abc");

System.out.println(s1 == s3);  //false

(2)"equals" ,字符串内容之间比较,区分大小写

String s1 = "abc";
String s2 = "abc";

boolean result1 = s1.equals(s2);
System.out.println(result1);    // true

String s3 = new String("abc");

boolean result2 = s1.equals(s3);
System.out.println(result2);  // true

String s4 = "Abc";

boolean result3 = s4.equals(s1);
System.out.println(result3);    // false  区分大小写

(3)"equalsIgnoreCase" 字符串比较忽略大小写

String s1 = "abc";
String s2 = "ABc";

boolean result = s1.equalsIgnoreCase(s2);  
System.out.println(result);    // true

注:键盘录入也是属于new

3、遍历字符串

将字符串转换为数组 :charAt()

String src = "abcd";

for(int i = 0; i < src.length(); i++){    //对数组用.length,对字符串用.length()

    char c = src.charAt(i);
    System.out.println(c);        // a b c d

}

4、字符串拼接和反转

(1)拼接

public class lqb {
	public static void main(String[] args) {
		
		int[] array = {1,2,3};
		System.out.print("[");
		for(int i = 0; i < array.length; i++) {
			System.out.print(i == array.length - 1? array[i] + "]" : array[i] + ", ");

		}
}

(2)反转

public class lqb {    
    public static void main(String[] args) {
		
		String src = "abcde";
		
		for(int i = src.length() - 1; i >= 0; i--) {
			System.out.print(src.charAt(i));

		}
    }
}
public class lqb {    
    public static void main(String[] args) {
		
		String src = "abcde";

        String result = "";
		for(int i = src.length() - 1; i >= 0; i--) {
			char c = src.charAt(i);
            result += c;

		}

        System.out.println(result);
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值