Skip to content

Latest commit

 

History

History
215 lines (144 loc) · 4.67 KB

[数据结构] 字符串操作.md

File metadata and controls

215 lines (144 loc) · 4.67 KB

在JAVA语言中,字符串数据实际上由String类所实现的。Java字符串类分为两类:一类是在程序中不会被改变长度的不变字符串;二类是在程序中会被改变长度的可变字符串。Java环境为了存储和维护这两类字符串提供了 String和StringBuffer两个类。

#String的一些常用操作

##字符串创建

 

String str="This is a String";

或者

String str=new String("This is a String");

  第一种的的效率比较高,详细的可以看:   String、StringBuffer与StringBuilder区别和联系(源码)

##字符串长度

String str= "This is a String";
int len =str.length();

##指定字符或子字符串的位置

  

String str="Thisis a String";
Int index1 =str.indexOf("i");   //2
Int index2=str.lastIndexOf("i"); //12

##判断两个字符串是否相等

String str="This is a String";
Boolean result=str.equals("This is another String");

##得到指定位置的字符

String str="This is a String";
char chr=str.charAt(3);

##截取子字符串

str=str.substring(int beginIndex);

 截取掉str从首字母起长度为beginIndex的字符串,将剩余字符串赋值给str;  

str=str.substring(int beginIndex,int endIndex);

 截取str中从beginIndex开始至endIndex结束时的字符串,并将其赋值给str;

##字符串合并

  

String str="This is a String";
String str1=str.concat("Test"); //str1="This is a String Test"

##字符串大小写的转换

str.toLowerCase(); 

大写转小写

str.toUpperCase(); 

小写转大写

##去掉字符串中开头和结尾处的空格

String str="This is a String   ";
String str1=str.trim();   //str1="This is a String"

#StringBuffer的一些常用操作

##初始化

 StringBuffer s = new StringBuffer();

这样初始化出的StringBuffer对象是一个空的对象。 如果需要创建带有内容的StringBuffer对象,则可以使用:

StringBuffer s = new StringBuffer(“abc”);

##append方法

  追加内容到当前StringBuffer对象的末尾,类似于字符串的连接。调用该方法以后,StringBuffer对象的内容也发生改变。

  

StringBuffer sb = new StringBuffer(“abc”);
  sb.append(true);

对象sb的值将变成”abctrue”

##deleteCharAt方法

删除指定位置的字符,然后将剩余的内容形成新的字符串

StringBuffer sb = new StringBuffer(“Test”);
 sb. deleteCharAt(1);

对象sb的值变为”Tst”

还存在一个功能类似的delete方法:

public StringBuffer delete(int start,int end)

该方法的作用是删除指定区间以内的所有字符,包含start,不包含end索引值的区间。

##insert方法

在StringBuffer对象中插入内容,然后形成新的字符串。

   StringBuffer sb = new StringBuffer(“TestString”);
  sb.insert(4,false);

在对象sb的索引值4的位置插入false值,形成新的字符串,则执行以后对象sb的值是”TestfalseString”。

##reverse方法

将StringBuffer对象中的内容反转,然后形成新的字符串

 StringBuffer sb = new StringBuffer(“abc”);
 sb.reverse();

对象sb中的内容将变为”cba”

##setCharAt方法

修改对象中指定索引值位置的字符为新的字符

 StringBuffer sb = new StringBuffer(“abc”);
 sb.setCharAt(1,’D’);

sb的值将变成”aDc”

##trimToSize方法

将StringBuffer对象的中存储空间缩小到和字符串长度一样的长度,减少空间的浪费。

#常见问题

  • 字符串比较,使用 "==" 还是 equals() ?

  源码分析equals与==的区别

  • 在switch语句中使用String作为case条件?

  Switch能否用string做参数?

  • String转换为数字
int age = Integer.parseInt("10");  
long id = Long.parseLong("190"); // 假如值可能很大.

  非常大的数字请使用Long

  • 通过空白字符拆分字符串
String[] strArray = aString.split("\\s+");  

  String 的 split()方法接收的字符串会被当做正则表达式解析,       "\s"代表空白字符,如空格" "(tab制表符"\t", 换行"\n",回车"\r")

  而编译器在对源代码解析时,也会进行一次字面量转码,所以需要"\s".

  • 将String转换为日期
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");  
String str = "2016-05-07";  
Date date = format.parse(str);  
System.out.println(format.format(date));