一些string(字符串的比较、分割、替换)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_34195441/article/details/86028007
package com.hpu.string;

import java.util.Arrays;

/**
 * final修饰变量为常量(只可赋值一次,不能再修改的)
 * final修饰类,这个类是不能被继承的
 * final修饰的方法,不能被重写
 * 
 * 字符串比较:==地址 ;equal值
//常量池
		String str1 = "hello";
		//
		String str2 = new String("hello");
		String str4 = new String("hello");
		String str3 = "hello";
		System.out.println(str2);
		//地址比较
		System.out.println(str1==str2);//false
		//比较值
		System.out.println(str1.equals(str2));//true
		System.out.println(str1==str3);//true
 * @author Administrator
 *
 */
public class TestString {
	public static void main(String[] args) {
		String str="helloworld";
		//忽略大小写比较
		boolean flag=str.equalsIgnoreCase("HelloWorld");
		System.out.println(flag);
		//根据下标获取对应的字符
		System.out.println(str.charAt(0));
		/*
		 * indexof:查看当前字符串中是否存在某个字符串,如果存在,返回下表
		 * 如果存在重复的字符串,默认返回第一个字符串的下标
		 * 如果不存在,返回-1
		 */
		int index=str.indexOf("h");
		System.out.println(index);
		//分割
		String str2="my name is haha";
		//根据空字符进行分割
		String [] strArray=str2.split(" ");
		System.out.println(Arrays.toString(strArray));
		//根据字符进行分割
		String [] strArray2=str2.split("");
		System.out.println(Arrays.toString(strArray2));
		
		
		//演示字符串为空时
		String str3=null;
		//str3.equals("hello");
		"hello".equals(str3);//会避免空指针异常
		System.out.println("hello".equals(str3));
		
		//替换
		String words="haha,hengheng";
		//replace支持链式操作
		words=words.replace("haha", "meng").replace("hengheng","ha").replace("ha","heng");
		System.out.println(words);
	}
}

猜你喜欢

转载自blog.csdn.net/qq_34195441/article/details/86028007