zoukankan      html  css  js  c++  java
  • 常使用的String方法

    public String()
    
    	public String(String original)
    	
    	public String(char[] value)
    	
    	public String(char[] value, int offset, int count)
    	
    	public String(byte[] bytes)
    	
    	public String(byte[] bytes, int offset, int length) 
    	
    	String(byte[] bytes, String charsetName) 
    	
    	java.lang.StringIndexOutOfBoundsException
    	异常名称: 字符串索引越界
    	产生原因: 访问了字符串所对应的字符数组的索引范围
    	解决办法: 自己检查索引是否超出了字符串的范围
    
    
    String s1 = "";
    		String s2 = new String();
    		
    		System.out.println(s1 == s2);
    		System.out.println(s1.equals(s2));
    		
    		// public String(String original)
    		//直接初始化
    		String s3 = new String("abc");
    		System.out.println(s3);
    		
    		// public String(char[] value)
    		//char数组转换成String字符串
    		char[] chs = {'a', 'b', 'c', 'd'};
    		String s4 = new String(chs);
    		System.out.println(s4);
    		
    		// public String(char[] value, int offset, int count)
    		//从offset索引开始,3个元素,转换成String字符串
    		String s5 = new String(chs, 0, 3);
    		System.out.println(s5);
    		
    		// public String(byte[] bytes)
    		//bytes数组转成int再String,97,98,99是a,c,b的转义字符
    		System.out.println(new String(new byte[] {97,98,99}));
    		
    		// public String(byte[] bytes, int offset, int length) 
    		//把bytes数组进行转换再从索引0开始截取2位
    		System.out.println(new String(new byte[]{97,98,99,100}, 0, 2));
    		
    		// String(byte[] bytes, String charsetName)
    		//中国你好进行格式转换,从UTF-8转乘gbk
    		String s6 = new String("中国你好".getBytes(), "gbk");
    		System.out.println(s6);
    
    结果:
    abc
    abcd
    abc
    abc
    ab
    中国你好
    
    char charAt(int index) 
    	int indexOf(int ch) 
    	int indexOf(String str) 
    	int indexOf(int ch,int fromIndex) 
    	int indexOf(String str,int fromIndex)
    	int lastIndexOf(int ch)    
    	int lastIndexOf(String str,int fromIndex) 
    	String substring(int start)
    	String substring(int start,int end)
    	int length()  
    	注意: length,length(),size()的区别
    length: 是数组的一个属性
    length(): 是字符串或者其他类的一个方法
     	size(): 是集合或者其他类的一个长度方法
    
    
    String s1 = "abchelloDEbhellofhello";
    		// char charAt(int index) 
    		// 截取索引0的转换成字符
    		char ch = s1.charAt(0);
    		System.out.println(ch);
    		System.out.println("-------------------");
    		// int indexOf(int ch) 
    		//输出'E'的下标
    		int index = s1.indexOf('E');
    		System.out.println("index:" + index);
    		System.out.println("-------------------");
    		// int indexOf(String str) 
    		//输出'bc'的下标
    		System.out.println("indexOf:" + s1.indexOf("bc"));
    		System.out.println("--------------------");
    		// int indexOf(int ch,int fromIndex) 
    		// 从fromIndex索引开始,查找第一次出现ch字符的索引
    		System.out.println("indexOf:" + s1.indexOf('b', 6));
    		System.out.println("--------------------");
    		// int indexOf(String str,int fromIndex)
    		System.out.println("indexOf:" + s1.indexOf("hello", 6));
    		System.out.println("--------------------");
    		// int lastIndexOf(int ch)
    		// int lastIndexOf(String str,int endIndex)
    		//到下标endIndex为止,str最后一次出现的下标
    		System.out.println("lastIndexOf:" + s1.lastIndexOf("hello", 18));
    		String s2 = "HelloWorldEverybody";
    		// String substring(int start)
    		//从下标start的开始,不包含start开始到末尾截取
    		String substring = s2.substring(5);
    		System.out.println(substring);
    		//String substring(int start,int end)
    		//从start下标开始,包含start,到end下标结尾,不包含end,进行截取
    		System.out.println(s2.substring(5, 10));
    		//从start下标开始,包含start,到end下标结尾,不包含end,进行截取,转换成CharSequence
    		CharSequence sequence = s2.subSequence(5, 10);
    		System.out.println(sequence);
    
    结果:
    a
    -------------------
    index:9
    -------------------
    indexOf:1
    --------------------
    indexOf:10
    --------------------
    indexOf:11
    --------------------
    lastIndexOf:17
    WorldEverybody
    World
    World
    
    
      boolean isEmpty():判断字符串是否为空。
    
    	boolean equals(Object obj):将此字符串的内容与指定的对象比较,区分大小写。
    	
    	boolean equalsIgnoreCase(String str):将此 String 与另一个 String 比较,忽略大小写。
    	
    	boolean contains(String str):判断字符串中是否包含方法传入的字符串。
    	
    	boolean startsWith(String str):判断字符串是否以某个指定的字符串开头。
    	
    	boolean endsWith(String str):判断字符串是否以某个指定的字符串结尾。
    	
    	boolean isEmpty():判断字符串是否为空。
    
    //		String s1 = "abchelloDEbhellofhello";
    		String s1 = "";
    		String s2 = new String();
    		String s3 = null;
    		
    //		System.out.println(s1.equals(s2)); //true
    //		System.out.println(s1.isEmpty()); // true
    //		System.out.println(s2.isEmpty()); // true
    //		System.out.println(s3.isEmpty()); // NullPointerException
    		String s4 = "Hello";
    		String s5 = "HelloWorld";
    		System.out.println(s4.equals(s5));
    		System.out.println(s4.equalsIgnoreCase(s5));
    		
    		System.out.println(s5.contains("AHelloWorld"));
    		
    		// boolean startsWith(String str):判断字符串是否以某个指定的字符串开头。
    		System.out.println(s5.startsWith("Hello"));
    		System.out.println(s5.endsWith("World"));
    
    
      byte[] getBytes() :将字符串转化为字节数组。
    	char[] toCharArray(): 将字符串转化为字符数组。
    	static String valueOf(char[] chs): 返回 char 数组参数的字符串表示形式。
    	static String valueOf(int i) :返回 int 参数的字符串表示形式。
    	String toLowerCase() :将此 String 中的所有字符都转换为小写。
    	String toUpperCase() :将此 String 中的所有字符都转换为大写。
    	String concat(String str): 将指定字符串连接到此字符串的结尾。
    
    public class Test {
    	public static void main(String[] args) throws IOException {
    		String s1 = "abcEFefg";
    		byte[] bys = s1.getBytes();//byte[] getBytes() :将字符串转化为字节数组。
    		for (int i = 0; i < bys.length; i++) {
    			byte b = bys[i];
    			System.out.println((char)b);
    		}
    		
    		System.out.println("-----------------------");
    		char[] chs = s1.toCharArray();//char[] toCharArray(): 将字符串转化为字符数组
    		System.out.println(Arrays.toString(chs));
    		for (int i = 0; i < chs.length; i++) {
    			char c = chs[i];
    			System.out.println((short)c);
    		}
    		
    		System.out.println("------------------------");
    		// static String valueOf(char[] chs): 返回 char 数组参数的字符串表示形式。
    		String result = String.valueOf(false);//String valueOf(char[] chs): 返回 char 数组参数的字符串表示形式。
    		System.out.println(result);
    		
    		System.out.println(String.valueOf(new Student()));
    		
    		System.out.println("-----------------------");
    		/*
    		 * String toLowerCase() :将此 String 中的所有字符都转换为小写。
    		   String toUpperCase() :将此 String 中的所有字符都转换为大写。
    		 */
    		System.out.println(s1.toLowerCase());
    		System.out.println(s1.toUpperCase());
    		
    		System.out.println("-------------------------");
    		// String concat(String str): 将指定字符串连接到此字符串的结尾。
    		String s2 = "Hello";
    		String s3 = "World";
    		String concat = s2.concat(s3);
    		System.out.println(concat);
    		
    		
    	}
    }
    
    class Student{
    	String name;
    
    	@Override
    	public String toString() {
    		return "Student [name=" + name + "]";
    	}
    }
    
    String replace(char old,char new) :替换功能。
    	String replace(String old,String new) :替换功能。
    	String trim():去除字符串前后两端空格。
    	int compareTo(String str) :按字典顺序比较两个字符串。
    	int compareToIgnoreCase(String str):按字典顺序比较两个字符串,忽略大小写。
    	public String[] split(String regex):分隔字符串成字符数组。
    
    public static void main(String[] args) throws IOException {
    		// String replace(char old,char new) :替换功能。
    				String s1 = "HelloWorldJava";
    				String replace1 = s1.replace('H', 'h');
    				System.out.println(replace1);
    				String replace2 = s1.replace("Java", "Android");
    				System.out.println(replace2);
    				String replace3 = s1.replaceAll("", "隔壁老王");//每个字母间都有""
    				System.out.println(replace3);
    				String replace4 = s1.replaceFirst("", "隔壁老王");//体会第一个
    				System.out.println(replace4);
    				
    				System.out.println("----------------------");
    				String s2 = "     Good   Good   Study      ";
    				System.out.println(s2.trim() + "-----------");//去除字符串前后两端空格
    				System.out.println("-----------------------");
    				// int compareTo(String str) :按字典顺序比较两个字符串。
    				String s3 = "abcd";
    				String s4 = "abdd";
    				int compareTo = s3.compareTo(s4);
    				int compareTo2 = s4.compareTo(s3);
    				System.out.println(compareTo);
    				System.out.println(compareTo2);
    				
    				System.out.println("---------------------");
    				String s5 = "G-o-o-d-Boy";
    				String[] strs = s5.split("-");//分隔字符串成字符数组
    				System.out.println(Arrays.toString(strs));
    	}
    }
    
    结果:
    helloWorldJava
    HelloWorldAndroid
    隔壁老王H隔壁老王e隔壁老王l隔壁老王l隔壁老王o隔壁老王W隔壁老王o隔壁老王r隔壁老王l隔壁老王d隔壁老王J隔壁老王a隔壁老王v隔壁老王a隔壁老王
    隔壁老王HelloWorldJava
    ----------------------
    Good   Good   Study-----------
    -----------------------
    -1
    1
    ---------------------
    [G, o, o, d, Boy]
    
    String s3 = "abcd";
    String s4 = "abdd";
    int compareTo = s3.compareTo(s4);
    int compareTo2 = s4.compareTo(s3);
    System.out.println(compareTo);
    System.out.println(compareTo2);
    
    结果:
    -1
    1
    

    compareTo源码解析

    String s3 = "abcd";
    	String s4 = "abdd";
    	int compareTo = s3.compareTo(s4);
    	
    	public int compareTo(String anotherString) {
            int len1 = value.length; "abcd"  4
            int len2 = anotherString.value.length; "abdd" 4
            int lim = Math.min(len1, len2); 
            char v1[] = value; "abcd"
            char v2[] = anotherString.value; "abcd"
    
            int k = 0;
            while (k < lim) {
                char c1 = v1[k]; a b c  
                char c2 = v2[k]; a b d
                if (c1 != c2) {
                    return c1 - c2; 99 - 100 -1
                }
                k++;
            }
            return len1 - len2;
        }
    
    

    所以说不等于0就是不相等

  • 相关阅读:
    什么是多线程中的上下文切换?
    java 中有几种方法可以实现一个线程?
    什么叫线程安全?servlet 是线程安全吗?
    什么是线程调度器(Thread Scheduler)和时间分片(Time Slicing )?
    一个线程运行时发生异常会怎样?
    我的样式
    springboot+dynamic多数据源配置
    mybatis plus条件拼接
    springboot配置虚拟路径
    springboot+mybatis+Druid配置多数据源(mysql+postgre)
  • 原文地址:https://www.cnblogs.com/zhangsonglin/p/11192141.html
Copyright © 2011-2022 走看看