Java常用对象API——String类

String类的特点:

字符串对象一旦被初始化就不会被改变。

     public static void stringDemo2() {
    		// TODO Auto-generated method stub
    		
    		String s = "abc";//创建一个字符串对象在常量池中。		
    		String s1 = new String("abc");//创建两个对象一个new一个字符串对象在堆内存中。
    		
    		System.out.println(s==s1);//false
    		
    		System.out.println(s.equals(s1));
    		//string类中的equals复写Object中的equals建立了string类自己的判断字符串对象是否相同的依据。
    		//其实就是比较字符串内容。
    		
    		
    //		System.out.println("s="+s);
    //		System.out.println("s1="+s1);
    		
    	}

构造函数:

将字节数组或者字符数组转成字符串可以通过String类的构造函数完成。

    public class StringConstructorDemo {
    
    	
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    
    		/*
    		 * 将字节数组或者字符数组转成字符串可以通过String类的构造函数完成。
    		 */
    		stringConstructorDemo();
    		stringConstructorDemo2();
    	}
    
    	private static void stringConstructorDemo2() {
    		char[] arr = {'w','a','p','q','x'};
    		String s = new String(arr,1,3); //第二个字符开始到第四个
    		
    		System.out.println("s="+s);
    	}
    
    	public static void stringConstructorDemo() {
    		String s = new String();//等效于String s = "";  不等效String s = null;
    		
    		byte[] arr = {97,66,67,68};
    		
    		String s1 = new String(arr);
    		System.out.println("s1="+s1);
    		
    	}
    }

运行结果:在这里插入图片描述

字符串常见功能分类

  • 1,获取:
    * 1.1 获取字符串中字符的个数(长度).
    * int length();
    * 1.2 根据位置获取字符。
    * char charAt(int index);
    * 1.3 根据字符获取在字符串中的第一次出现的位置.
    * int indexOf(int ch)
    * int indexOf(int ch,int fromIndex):从指定位置进行ch的查找第一次出现位置
    * int indexOf(String str);
    * int indexOf(String str,int fromIndex);
    * 根据字符获取在字符串中的最后一次出现的位置.
    * int lastIndexOf(int ch)
    * int lastIndexOf(int ch,int fromIndex):从指定位置进行ch的查找第一次出现位置
    * int lastIndexOf(String str);
    * int lastIndexOf(String str,int fromIndex);
    * 1.4 获取字符串中一部分字符串。也叫子串.
    * String substring(int beginIndex, int endIndex)//包含begin 不包含end 。
    * String substring(int beginIndex);
       private static void stringMethodDemo_1() {
    		
        	String  s = "abcdae";
        	
        	System.out.println("length:"+s.length());//6
        	System.out.println("char:"+s.charAt(2));//c//StringIndexOutOfBoundsException
        	System.out.println("index:"+s.indexOf('k'));//0//-1 我们可以根据-1,来判断该字符或者字符串是否存在。
        	System.out.println("lastIndex:"+s.lastIndexOf('a'));//4
        	
        	
        	System.out.println("substring:"+s.substring(2,4));//cd
        }
  • 2,转换。
    * 2.1 将字符串变成字符串数组(字符串的切割)
    * String[] split(String regex):涉及到正则表达式.
    * 2.2 将字符串变成字符数组。
    * char[] toCharArray();
    * 2.3 将字符串变成字节数组。
    * byte[] getBytes();
    * 2.4 将字符串中的字母转成大小写。
    * String toUpperCase():大写
    * String toLowerCase():小写
    * 2.5 将字符串中的内容进行替换
    * String replace(char oldch,char newch);
    * String replace(String s1,String s2);
    * 2.6 将字符串两端的空格去除。
    * String trim();
    * 2.7 将字符串进行连接 。
    * String concat(string);
      private static void stringMethodDemo_2() {
        	String  s = "张三,李四,王五";
        	String[] arr = s.split(",");
    	
    	for (int i = 0; i < arr.length; i++) {
    		System.out.println(arr[i]);
    	}
    	
    	char[] chs = s.toCharArray();
    	
    	for (int i = 0; i < chs.length; i++) {
    		System.out.println(chs[i]);
    	}
    	
    	System.out.println();
    	s = "ab你";
    	byte[] bytes = s.getBytes();
    	for (int i = 0; i < bytes.length; i++) {
    		System.out.println(bytes[i]);
    	}
    	System.out.println();
    	System.out.println("Abc".toUpperCase());
    	
    	System.out.println();
    	String s1 = "java";
    	String s2 = s1.replace('q', 'z');
    	System.out.println(s1==s2);//true
    	System.out.println();
    	System.out.println("-"+"    ab  c    ".trim()+"-");//去除两端空格
    	}

在这里插入图片描述

  • 3,判断
    * 3.1 两个字符串内容是否相同
    * boolean equals(Object obj);
    * boolean equalsIgnoreCase(string str);忽略大写比较字符串内容。
    * 3.2 字符串中是否包含指定字符串?
    * boolean contains(string str);
    * 3.3 字符串是否以指定字符串开头。是否以指定字符串结尾。
        private static void stringMethodDemo_3() {
		String s = "abc";
		System.out.println(s.equals("ABC".toLowerCase())); //true
		System.out.println(s.equalsIgnoreCase("ABC"));//true
		
		System.out.println(s.contains("cc"));//false
		
		String str  = "ArrayDemo.java";
		
		System.out.println(str.startsWith("Array"));//true

		System.out.println(str.endsWith(".java"));//true

		System.out.println(str.contains("Demo"));//true

		 }

4,比较。

   private static void stringMethodDemo_4() {
		 		System.out.println("abc".compareTo("aqz")); 	}

返回-15 表示小于

相关练习

一、给定一个字符串数组,按照字典顺序进行从小到大的排序。

关键:字符串对象比较功能——compareTo来比大小
/*

     * {"nba","abc","cba","zz","qq","haha"}
     * 
     * 思路:
     * 1,对数组排序。可以用选择,冒泡都行。
     * 2,for嵌套和比较以及换位。
     * 3,问题:以前排的是整数,比较用的比较运算符,可是现在是字符串对象。
     *   字符串对象怎么比较呢?爽了,对象中提供了用于字符串对象比较的功能。
     * 
     * 
     */
	public class StringTest_1 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		String[] arr = { "nba", "abc", "cba", "zz", "qq", "haha" };

		printArray(arr);

		sortString(arr);

		printArray(arr);

	}

	public static void sortString(String[] arr) {

		for (int i = 0; i < arr.length - 1; i++) {
			for (int j = i + 1; j < arr.length; j++) {

				if (arr[i].compareTo(arr[j]) > 0)// 字符串比较用compareTo方法
					swap(arr, i, j);
			}
		}
	}

	public static void swap(String[] arr, int i, int j) {
		String temp = arr[i];
		arr[i] = arr[j];
		arr[j] = temp;
	}

	public static void printArray(String[] arr) {
		System.out.print("[");
		for (int i = 0; i < arr.length; i++) {
			if (i != arr.length - 1)
				System.out.print(arr[i] + ", ");
			else
				System.out.println(arr[i] + "]");
		}
	  } 
	 }




二、求一个子串在整串中出现的次数

方法1:使用int indexOf(String str)

      public static int getKeyStringCount(String str, String key) {
		
		//1,定义计数器。 
		int count = 0;
		
		//2,定义变量记录key出现的位置。
		int index = 0;
		
		while((index = str.indexOf(key))!=-1){
			
			str = str.substring(index+key.length());
			count++;
		}
		return count;
	}

方法2:使用int indexOf(String str,int fromIndex)

这种方法较好,因为不需要在内存中产生过多的字符串常量

    public static int getKeyStringCount_2(String str, String key) {
    	
    	int count = 0;
    	int index = 0;
    	
		while((index = str.indexOf(key,index))!=-1){
			
			index = index + key.length();
			count++;
			
		}
		
		return count;
	}

三、求两个字符串中最大相同的子串

关键:substring(取子串)、contains(确定是否包含)。

    /*
     * 
     * "qwerabcdtyuiop"
     * "xcabcdvbn"
     * 
     * 思路:
     * 1,既然取得是最大子串,先看短的那个字符串是否在长的那个字符串中。
     * 如果存在,短的那个字符串就是最大子串。
     * 2,如果不是呢,那么就将短的那个子串进行长度递减的方式去子串,去长串中判断是否存在。
     * 如果存在就已找到,就不用在找了。
     * 
     * 
     */
    public class StringTest_3 {
    
    
    	public static void main(String[] args) {
    
    		String s1 = "qwerabcdtyuiop";
    		String s2 = "xcabcdvbn";
    
    		String s = getMaxSubstring(s2, s1);
    		System.out.println("s=" + s);
    	}
    
    
    	public static String getMaxSubstring(String s1, String s2) {
    		
    		String max = null,min = null;
    		max = (s1.length()>s2.length())?s1:s2;
    		
    		min = max.equals(s1)?s2:s1;   //保证用长度小的字符串来比较
    		
    		System.out.println("max="+max);
    		System.out.println("min="+min);
    		
    		
    		
    		for (int i = 0; i < min.length(); i++) {
    			
    			for(int a = 0,b = min.length()-i; b != min.length()+1; a++,b++){
    				
    				String sub = min.substring(a, b);
    //				System.out.println(sub);
    				if(max.contains(sub))
    					return sub;
    			}
    		}
    		
    		return null;
    	}
    }

四、模拟一个trim功能一致的方法,去除字符串两端的空白

  • 思路:
  • 1,定义两个变量。
  • 一个变量作为从头开始判断字符串空格的角标。不断++。
  • 一个变量作为从尾开始判断字符串空格的角标。不断–。
  • 2,判断到不是空格为止,取头尾之间的字符串即可。
  • 关键:s.charAt(start)与s.charAt(end)来处理首尾字符
          public class StringTest_4 {
        	public static void main(String[] args) {
        
    		String s = "    ab   c     ";
    
    		s = myTrim(s);
    		System.out.println("-" + s + "-");
    	}
    
    	public static String myTrim(String s) {
    
    		int start = 0, end = s.length() - 1;
    
    		while (start <= end && s.charAt(start) == ' ') {
    			start++;
    		}
    		while (start <= end && s.charAt(end) == ' ') {
    			end--;
    		}
    		return s.substring(start, end + 1);
    	 } 
    	 }

猜你喜欢

转载自blog.csdn.net/z714405489/article/details/82831829