黑马程序员——java编程那些事儿____String类

                                                                                         -------android培训java培训、期待与您交流! ----------


String类  字符串


(1)多个字符组成的一个序列,叫字符串。

   生活中很多数据的描述都采用的是字符串的。而且我们还会对其进行操作。

   所以,java就提供了这样的一个类供我们使用。


(2)创建字符串对象

A:String():无参构造

**举例:

  String s = new String();

  s = "hello";

  sop(s);

B:String(byte[] bys):传一个字节数组作为参数 *****

**举例

  byte[] bys = {97,98,99,100,101};

  String s = new String(bys);

  sop(s);

C:String(byte[] bys,int index,int length):把字节数组的一部分转换成一个字符串 *****

**举例

  byte[] bys = {97,98,99,100,101};

  String s = new String(bys,1,2);

  sop(s);

D:String(char[] chs):传一个字符数组作为参数 *****

**举例

  char[] chs = {'a','b','c','d','e'};

  String s = new String(chs);

  sop(s);

E:String(char[] chs,int index,int length):把字符数组的一部分转换成一个字符串 *****

**举例

  char[] chs = {'a','b','c','d','e'};

  String s = new String(chs,1,2);

  sop(s);

F:String(String str):把一个字符串传递过来作为参数

**举例

   String str = "abcdef";

  String ss = new String(str);

  sop(ss);

G:直接把字符串常量赋值给字符串引用对象(最常用) *****

**举例

  String s = "hello";

  sop(s);


(3)字符串特点(字符串一旦被初始化就不可以被改变,指的是字符串常量不变


class StringDemo 
{
	public static void main(String[] args) 
	{

		/*
		字符串最大特点:一旦被初始化就不可以被改变。	


		String s1 = "abc";//s1是一个类类型变量,"abc"是一个对象。
						 
		String s2 = new String("abc");

		s1和s2有什么区别?
			s1在内存中有一个对象。
			s2在内存中有两个对象。一个“abc”字符串对象在方法区的常量池,一个s2对象在栈内存
		

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

		System.out.println(s1.equals(s2));//true
										  //String类复写了Object类中equals方法,该方法用于判断字符串是否相同。
									
		*/

	}
}


***三道面试题

A:请问String s = new String("hello");创建了几个对象。

  两个。一个"hello"字符串对象,在方法区的常量池;一个s对象,在栈内存。

B:请写出下面的结果

String s1 = new String("abc");

Strign s2 = new String("abc");

String s3 = "abc";

String s4 = "abc";

sop(s1==s2);  //false

sop(s1==s3);  //false

sop(s3==s4);  //true

C:字符串对象一旦被创建就不能被改变。

指的是字符串常量值不改变。



(4)字符串中各种功能的方法


A: 判断

**** boolean equals(Object anObject):判断两个字符串的内容是否相同,复写了Object的方法

**** boolean equalsIgnoreCase(String anotherString):判断两个字符串的内容是否相同,

                                             不区分大小写

**** boolean contains(String s):判断一个字符串中是否包含另一个字符串

                       注意:判断字符串是否包含特殊字符.直接表示为str.contains(".")

                              特殊之处:indexOf(str):可以索引str第一次出现位置,如果返回-1.表示该str不在字符串中存在。所以,也可以用于对指定判断是否包含。

                                                   if(str.indexOf("aa")!=-1)  ,  而且该方法即可以判断,又可以获取出现的位置。

**** boolean endsWith(String suffix):测试此字符串是否以指定的后缀结束

**** boolean startsWith(String suffix):测试此字符串是否以指定的前缀开始

**** boolean isEmpty():测试字符串是否为空

//判断
	public static void method_is()
	{
		String str = "ArrayDemo.java";
		//判断文件名称是否是Array单词开头
		sop(str.startsWith("Array"));
		//判断文件名称是否是.java结尾
		sop(str.endsWith(".java"));
		//判断文件中是否包含Demo
		sop(str.contains("Demo"));
	}

B: 获取

***** int length():返回此字符串的长度

***** char charAt(int index):返回指定索引处的 char

***** int indexOf(int ch):返回指定字符在此字符串中第一次出现处的索引。 

int indexOf(int ch, int fromIndex):返回在此字符串中第一次出现指定字符处的索引,从指定的索引开始搜索。 

int indexOf(String str):返回指定子字符串在此字符串中第一次出现处的索引。 

int indexOf(String str, int fromIndex):返回指定子字符串在此字符串中第一次出现处的索引,从指定的索引开始。 

*** int lastIndexOf(int ch):返回指定字符在此字符串中最后一次出现处的索引。 

int lastIndexOf(int ch, int fromIndex) 返回指定字符在此字符串中最后一次出现处的索引,从指定的索引处开始进行反向搜索。 

int lastIndexOf(String str) 返回指定子字符串在此字符串中最右边出现处的索引。 

int lastIndexOf(String str, int fromIndex) 返回指定子字符串在此字符串中最后一次出现处的索引,从指定的索引开始反向搜索。 

***** String substring(int beginIndex) (注意:该方法substringString是小写!!!)返回一个新的字符串,它是此字符串的一个子字符串。 

String substring(int beginIndex, int endIndex) (注意该方法的String是小写!!!)返回一个新字符串,它是此字符串的一个子字符串,包含头

                                                   不包含尾。 

	//获取
	public static void method_get()
	{
		String str = "abcdeapkf";
		//长度
		sop(str.length());
		//根据索引获取字符
		sop(str.charAt(4));//当访问到字符串中不存在的角标时会发生StringIndexOutOfBoundsException(角标越界)
		//根据字符获取索引
		sop(str.indexOf("a",3));//如果没有找到,返回-1
		//反向索引一个字符出现的位置
		sop(str.lastIndexOf("a"));
	}


C:转换


***将字符数组转成字符串。


构造函数: 

String(char[])

 String(char[],offset,count):将字符数组中的一部分转成字符串。

静态方法:

static String copyValueOf(char[]);

static String copyValueOf(char[] data, int offset, int count) 

static String valueOf(char[]):


***将字符串转成字符数组。

char[] toCharArray():

***将字符串转成字节数组

byte[]  getBytes():

  ***将字节数组转成字符串。

        String(byte[])

               String(byte[],offset,count):将字节数组中的一部分转成字符串。

               特殊:字符串和字节数组在转换过程中,是可以指定编码表的。


   ***将基本数据类型转成字符串。
static String valueOf(int)
static String valueOf(double)

//3+"";//String.valueOf(3);

//转化
	public static void method_trans()
	{
		char[] arr = {'a','b','c','d','e','f'};
		String s = new String(arr,1,3);//字符数组转化为字符串
		sop("s="+s);

		String s1 = "zxcvbnm";
		char[] chs = s1.toCharArray();//字符串转化为字符数组
		for (int x=0;x<chs.length ;x++ )
		{
			sop("ch="+chs[x]);
		}
	}

D:替换

String replace(char oldChar, char newChar):用新字符替换旧字符(替换所有)

String replace(String target, String replacement):用新的子串换旧串

	//替换
	public static void method_replace()
	{
		String s = "hello java";
		String s1 = s.replace('a','n');//如果要替换的字符不存在,返回的还是原串
		String s2 = s.replace("java","haha");
		sop("s="+s);
		sop("s1="+s1);
		sop("s2="+s2);
	}


E:切割

String[] split(String regex):根据指定的字符串把一个字符串分割成一个字符串数组

	//切割
	public static void method_split()
	{
		String s = "zhangshan,lisi,wangwu";
		String[] arr = s.split(",");
		for (int x=0;x<arr.length ;x++ )
		{
			sop(arr[x]);
		}
	}


F:字串(获取字符串中的一部分)

     String substring(begin,end);

String substring(begin);

	//字串
	public static void method_sub()
	{
		String s = "abcdef";
		sop(s.substring(2));//从指定位置开始到结尾。如果角标不存在,会出现字符串角标越界异常
		sop(s.substring(2,4));//包含头,不包含尾。如果获取全部字符串则s.substring(0,s.length());
	}

G:去除空格

String trim():去除字符串的前后空格


H:转换大小写

String toUpperCase();转化成大写

   String toLowerCase();转化成小写


I:比较

int compareTo(String anotherString) 

按字典顺序比较两个字符串。 

int compareToIgnoreCase(String str) 

按字典顺序比较两个字符串,不考虑大小写。

public static void method_7()
	{
		 String s = "   hello java   ";
		 sop(s.toLowerCase());
		 sop(s.toUpperCase());
		 sop(s.trim());

		 String s1 = "abc";
		 String s2 = "aaa";
		 sop(s1.compareTo(s2));
	}



(5)练习


练习一  去除字符串两端的空格

思路:

1,判断字符串第一个位置是否是空格,如果是继续向下判断,直到不是空格为止。结尾处判断空格也是如此。
2,当开始和结尾都判断到不是空格时,就是要获取的字符串。

class  StringTest
{
	public static void sop(String str)
	{
		System.out.println(str);
	}

	public static void main(String[] args) 
	{
		String s = "    ab cd    ";
		sop("["+s+"]");
		s = myTrim(s);
		sop("["+s+"]");
	}	

	public static String myTrim(String str)
	{
		int start=0,end=str.length()-1;
		while(start<=end && str.charAt(start)==' ')
			start++;
		while(start<=end && str.charAt(end)==' ')
			end--;
		return str.substring(start,end+1);
	}
}



练习二 将字符串反转

思路:

1,曾经学习过对数组的元素进行反转。
2,将字符串变成数组,对数组反转。
3,将反转后的数组变成字符串。
4,只要将或反转的部分的开始和结束位置作为参数传递即可。

class  StringTest
{
	public static void sop(String str)
	{
		System.out.println(str);
	}

	public static void main(String[] args) 
	{
		String s = "    ab cd    ";
		sop("["+s+"]");

		sop("["+reverseString(s)+"]");//练习二
		sop("["+reverseString(s)+"]");//整串反转    //练习二 特例
		sop("["+reverseString(s,4,5)+"]");//部分反转//练习二 特例
	}

	//练习二  将字符串反转
	/*
	思路:
	1,将字符串变成数组。
	2,对数组反转。
	3,将数组变成字符串。
	*/

	public static String reverseString(String s)
	{
		char[] chs = s.toCharArray();//字符串变数组
		reverse(chs);//反转数组
		return new String(chs);//将数组变成字符串
	}
	private static void reverse(char[] arr)
	{
		for(int start=0,end=arr.length()-1; start<end; start++,end--)
		{
			swap(arr,start,end);
		}
	}
	private static void swap(char[] arr,int x,int y)
	{
		char temp = arr[x];
		arr[x] = arr[y];
		arr[y] = temp;
	}
	
	//练习二 特例 将部分字符串反转,比如说将ab反转
	public static String reverseString(String s,int start,int end)
	{
		char[] chs = s.toCharArray();//字符串变数组
		reverse(chs,start,end);//反转数组
		return new String(chs);//将数组变成字符串
	}
	public static String reverseString(String s)
	{
		
		return reverseString(s,0,s.length());//整串反转,其实是调用上面的函数
		return "";//部分反转
		
	}
	private static void reverse(char[] arr,int x,int y)
	{
		for(int start=x,end=y-1; start<end; start++,end--)//包含头不包含尾
		{
			swap(arr,start,end);
		}
	}
	private static void swap(char[] arr,int x,int y)
	{
		char temp = arr[x];
		arr[x] = arr[y];
		arr[y] = temp;
	}
}

练习三  获取一个字符串在另一个字符串中出现的次数

思路:
1,定义个计数器。
2,获取kk第一次出现的位置。
3,从第一次出现位置后剩余的字符串中继续获取kk出现的位置。每获取一次就计数一次。
4,当获取不到时,计数完成。
class StringTest2 
{
	//方法一
	public static int getSubCount(String str,String key)
	{
		int count = 0;
		int index = 0;
		while ((index=str.indexOf(key))!=-1)
		{
			sop("str="+str);
			str = str.substring(index+key.length());
			count++;
		}
		return count;
	}

	//方法二
    public static int getsubCount_2(String str,String key)
	{
		int count = 0;
		int index = 0;
		while ((index=str.indexOf(key,index))!=-1)
		{
			sop("index="+index);
			index = index + key.length();
			count++;
		}
		return count;
	}

	public static void main(String[] args) 
	{
		String str = "abkkcdkkefkkskk";
		sop("count="+getSubCount(str,"kk"));//方法一
		sop("count="+getsubCount_2(str,"kk"));//方法二
	}
	public static void sop(String str)
	{
		System.out.println(str);
	}
}



练习四 获取两个字符串中最大相同字串


"abcwerthelloyuiodef"
   "cvhellobnm"
思路:
1,将短的那个子串按照长度递减的方式获取到。

2,将每获取到的子串去长串中判断是否包含,如果包含,已经找到!。

class  StringTest3
{
	public static String getMaxSubString(String s1,String s2)
	{
		String max = "",min = "";
		max = (s1.length()>s2.length())?s1:s2;
		min = (max==s1)?s2:s1;
		for (int x=0;x<min.length() ;x++ )
		{
			for (int y=0,z=min.length()-x;z!=min.length()+1 ;y++,z++ )//z!=min.length()+1的时候停
			{
				String temp = min.substring(y,z);
				if(s1.contains(temp))//或者if(s1.indexof(temp)!=-1)
					return temp;
			}
		}
		return "";
	}
	public static void main(String[] args) 
	{
		String s1 = "abcwerthelloyuiodef";
		String min = "cvhelloobnm";
		sop(getMaxSubString(s1,min));
	}
	public static void sop(String str)
	{
		System.out.println(str);
	}
}


练习五  对字符串中字符进行自然顺序排序

思路:
1,字符串变成字符数组。
2,对数组排序,选择,冒泡,Arrays.sort();
3,将排序后的数组变成字符串



二 StringBuffer


(1)字符串的缓冲区,是一个容器。而且这个容器长度可变,可以直接操作多个数据类型,具有存储,删除,获取,修改的操作,最终会通过toString方法变成字符串

(2)它和String的区别

它是缓冲区可变长度的。

(3)构造方法

StringBuffer() 构造一个其中不带字符的字符串缓冲区,初始容量为 16 个字符。

StringBuffer(int num) 构造一个不带字符,但具有指定初始容量的字符串缓冲区。

StringBuffer(String str) 构造一个字符串缓冲区,并将其内容初始化为指定的字符串内容。

(4)常用方法   C create U update R read D delete


1,存储。
StringBuffer append():将指定数据作为参数添加到已有数据结尾处。
StringBuffer insert(index,数据):可以将数据插入到指定index位置。


2,删除。
StringBuffer delete(start,end):删除缓冲区中的数据,包含start,不包含end。

StringBuffer deleteCharAt(index):删除指定位置的字符。


3,获取。
char charAt(int index) 
int indexOf(String str) 
int lastIndexOf(String str) 
int length() 
String substring(int start, int end) 
 
4,修改。
StringBuffer replace(start,end,string);
void setCharAt(int index, char ch) ;

5,反转。
StringBuffer reverse();
 
6, 将缓冲区中指定数据存储到指定字符数组中。

void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)


class StringBufferDemo 
{
	public static void main(String[] args) 
	{
		//method_append_insert();
		//method_delete();
		//method_update();
		method_getChars();
	}

	public static void sop(String str)
	{
		System.out.println(str);
	}

	public static void method_getChars()
	{
		StringBuffer sb = new StringBuffer("abcdef");
		char[] chs = new char[6];
		
		sb.getChars(1,4,chs,1);
		for(int x=0;x<chs.length;x++)
		{
			sop("chs["+x+"]="+chs[x]+";");
		}
	}

	public static void method_update()
	{
		StringBuffer sb = new StringBuffer("abcde");

		sb.replace(1,4,"java");
		sb.setCharAt(2,'k');

		sop(sb.toString());
	}

	public static void method_delete()
	{
		StringBuffer sb = new StringBuffer("abcde");

		sb.delete(1,3);
		//sb.delete(0,sb.length());//清空缓冲区
		sb.delete(2,3);//删一个
		sb.deleteCharAt(2);//删一个

		sop(sb.toString());
	}

	public static void method_append_insert()
	{
		StringBuffer sb = new StringBuffer();

        sb.append("abc").append(true).append(34);//方法调用链
									//(返回的是本类对象还能调用本类方法)
		
		sb.insert(1,"qq");//aqqbctrue34

		sop(sb.toString());
	}
}


三   字符串和StringBuffer的转换

String-->StringBuffer通过构造:

:StringBuffer sb = new StringBuffer(String str)

StringBuffer--String通过toString方法 

:StringBuffer sb = new StringBuffer();

   sb.toString();



四 StringBuilder


StringBuffer的功能是一样的,但是有区别:

StringBuffer(JDK1.0)是线程安全的。

StringBuilder(JDK1.5)不保证线程安全。

一般来说,我们写的程序都是单线程的,所以,用StringBuilder,效率高。

JDK版本的升级原则:

A:提高效率

B:提高安全性

C:简化书写



  -------android培训java培训、期待与您交流! ----------

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值