一、字符串相关类String, StringBuffer
- String
java.lang.String代表不可变的字符串序列,实现了Serializable,Comparable<String>,charSequence接口
String =""; 与 String = new String()创建出来的字符串存放位置并不相同,前者存放在数据区,而后者存放在堆里,对于放置于数据区的字符串采用懒惰策略,就是如果两个字符串内容一样,则指向数据区中同一个内存空间,但是如果要改变其中一个字符串就要重新给它分配一个内存空间,而对于new出的实例对象,堆里会直接分配新空间,而不共享,修改时同样会去建一个新对象。
public class TestString {
public static void main(String args[]) {
String s1 = "hello";
String s2 = "hello";
System.out.println(s1 == s2);
String s3 = new String("hello");
String s4 = new String("hello");
System.out.println(s1 == s3);
System.out.println(s1.equals(s3));
System.out.println(s3 == s4);
System.out.println(s3.equals(s4));
}
}
结果:true/false/true/false/true
String s1 = "hello";
String s2 = "world";
s1 = s1 + s2;
"hello"和"world"都在数据区中,后面连接字符串的时候,数据区中会自动开辟另一个空间,将“hello”和“world”复制进去,然后将s1引用指向他,并不改变之前的"hello"和“world”两个区域,后面系统会自动回收
主要构造函数:
- String() 空字符串
- String(char[])
- String(char[], offset, count)
String(c,4,5)表示从c[4]开始
- String(byte[]) String(byte[], Charset)
- String(String) 这个就是复制一个字符串
复习:Object.toString,getClass().getName+'@'+Integer.toHexString(hashCode()),一般会重写这个方法
主要方法(本来想做个表格,但是太懒了):
- charAt(index)
- compareTo(String),判断内容是否相同
compareToIgnoreCare(String)
lexicographically(字典序): 判断组成字母是否相同,如果相同,判断长度
相等 - 返回0
小于 - 返回负数
大于 - 返回正数
- contains(CharSequence)
- concat(String) 将参数字符串连到还字符串后面
- endsWith(String)
- startsWith(String)
- equals(Object)
equalsIgnoreCase(String)
返回true和false
- getChars(srcBegin, srcEnd, char[] dst, int dstBegin)
- hashCode()
- indexOf(String)
indexOf(String str, int begin),这个方法还挺常用的
indexOf(int ch)
- isEmpty()
- length()
- join(分隔符,元素)
静态方法
String message = String.join("-", "java", "is", "cool");
结果:java-is-cool
- matches(String)
正则匹配
- replace(旧,新)
replaceAll(正则表达式,替代)
replaceFirst(正则表达式,替代)
- split(正则表达式),返回字符串数组
- subSequence(begin, end) 返回CharSequence类型
CharSequence VS String
CharSequence是一个接口,实现它的类有String, StringBuffer,CharBuffer等
- substring(begin, end) 返回字符串
subString(begin)
- toCharArray() 返回新字符序列
- toLowerCase()
toUpperCase()
- trim()
- valueOf(Object obj) 返回对象参数的字符串表示
静态函数, Object.toString()
Object obj = new Long/Double/Integer/...(value);
obj.toString(); 动态绑定(多态)
比如:valueOf(long l) ,会调用Long.toString(long)
valueOf(int i)
valueOf(float f)
valueOf(double d)
valueOf(char[] data, int offset, int count)
valueOf(boolean b)
valueOf(char c)
valueOf(char[] data)
2. 习题:
/**
* 计数一个字符串里面有多少个数字,大写字母,小写字母和符号的个数
* 方法很多,可以用indexOf, contains或者ASCII码比较
*/
public class CountNumbers {
public static void main(String[] args) {
String str = "sdsajj214324@#nnSSDSF0#";
int dcount = 0, lcount = 0, ucount = 0, ncount = 0;
for(int i = 0; i < str.length(); i ++) {
char a = str.charAt(i);
if(Character.isAlphabetic(a)) {
if(Character.isLowerCase(a))
lcount ++;
else ucount ++;
} //不要忘了这个大括号哦~
else if(Character.isDigit(a))
dcount ++;
else
ncount ++;
}
System.out.println("ucount:"+ucount+" lcount:"+lcount+" dcount:"+dcount+" ncount:"+ncount);
}
}
/**
* 计数一个字符串里面出现某个子字符串的次数
*/
import java.util.*;
public class CountNumbers {
public static void main(String[] args) {
String str = "StringBuffer and String sound like the same thing, while it's not.\n String type is immutable and yet StringBuffer is not.";
String matchSubStr = "String";
int tmp = -1, count = 0, beginIdx = 0;
while((tmp = str.indexOf(matchSubStr, beginIdx)) >= 0) {
count++;
beginIdx = tmp + matchSubStr.length();
}
System.out.print(count);
}
}
- StringBuffer
- append(参数) 将参数的字符串表达式加在末尾,因为会返回,所以可以
sb.append(参数).append(参数)......
- insert(offset, 被插入数据) 在某个指定位置插入字符序列,返回
- delete(start, end) 删除从start开始到end-1为止的一段字符序列,返回
- substring(start)
substring(start, end) 注意不包括end
- length()
- reverse() 将字符序列逆序并返回
- 基本数据类型包装类
public class TestString {
public static void main(String args[]) {
double d1 = Double.parseDouble("3.14");
double d2 = Double.valueOf("2.15").doubleValue();
System.out.println("d1:"+d1+" d2:"+d2);
System.out.println(Integer.toBinaryString(123)+"B");
System.out.println(Integer.toHexString(123)+"H");
System.out.println(Integer.toOctalString(123)+"O");
}
}
- Math
- File
import java.io.*;
public class TestFile {
public static void main(String[] args) {
File f = new File("Root_/A/"+"1.txt");
File f1 = new File("Root_/B/");
File f2 = new File("Root_/C/E/"+"2.txt");
if(f.exists()){
System.out.println("文件绝对路径:"+f.getAbsolutePath());
System.out.println("文件大小:"+f.length());
}
else {
f.getParentFile().mkdirs();
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
if(f1.exists()){
System.out.println("文件绝对路径:"+f1.getAbsolutePath());
System.out.println("文件大小:"+f1.length());
}
else {
//f1.getParentFile().mkdirs();
try {
f1.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
if(f2.exists()){
System.out.println("文件绝对路径:"+f2.getAbsolutePath());
System.out.println("文件大小:"+f2.length());
}
else {
f2.getParentFile().mkdirs();
try {
f2.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
利用递归来遍历目录:
import java.io.*;
public class ListDirAndFile {
public static void main(String args[]) {
File file = new File("Root_");
getFile(file,"");
}
static void getFile(File file, String sp) {
System.out.println(sp+file.getName()); //print the name of the file
sp += " ";
if(!file.isDirectory()) return; //if it's file, stop
File[] childs = file.listFiles();
for(int i = 0; i < childs.length; i++) {
getFile(childs[i], sp);
}
}
}
- 枚举
枚举类是java.lang.Enum类型,使用enum关键字实现定义了一个枚举类型,只能够取特定值的一个,可以实现特定的接口
public class TestEnum {
public enum color {red, green, blue};
public static void main(String args[]) {
color c = color.red;
switch(c) {
case red:
System.out.println("red1");
break;
case blue:
System.out.println("blue1");
break;
case green:
System.out.println("green1");
break;
default:
System.out.println("default");
}
System.out.println(c);
}
}
其实枚举的优点:
- 安全性,比如public void method(ColorEnum enum) {},就只能传递给它枚举定义的值(每个值都是public final static的,每个值都相当于一个实例),这样用户就不能传递别的,因为可能用户传递了一个非预期的值,引发潜在的不安全性。
- 相当于定义了一组常量值,拥有更好的可读性
1. 枚举类型提供了两个静态方法values(),valueOf(),我们可以很方便的使用他们,
for(color c:color.values())
System.out.println(c);
valueOf()是把字符串类型转换为定义的枚举类型,比如valueOf("Blue")会返回color.Blue
2. toString()默认返回字符串,color.Blue.toString()会返回“Blue”,可以重写
3. 枚举类型中的构造函数不能是public或protected的,但是可以有private的,在enum内部使用,而且enum中可以定义方法和变量,这些要放在枚举值定义的后面,除此之外,我们还可以为每个枚举值定义方法
public class TestEnum {
//为每个颜色添加说明信息,然后定义了一个构造函数接受这个说明信息
public enum color {
red("this is red"),
green("this is green"),
blue("this is blue"),
cyan("this is cayn")
{
public String toString() {
return "I'm Cyan";
}
};
private String desc;
color(String desc) {
this.desc = desc;
}
public void printDesc() {
System.out.println(desc);
}
public String toString() {
switch(this) {
case red:
return "Color.Red";
case green:
return "Color.Green";
case blue:
return "Color.Blue";
case cyan:
return "Color.Cyan";
default:
return "Unknown Color";
}
}
}
public static void main(String args[]) {
color c = color.red;
System.out.println(c.toString());
c.printDesc();
color c1 = color.cyan;
System.out.println(c1.toString());
c1.printDesc();
}
}
结果:
Color.Red
this is red
I'm Cyan
this is cayn
Reference:
1. 马士兵JAVA基础视频
2. http://blog.sina.com.cn/s/blog_697b968901013ih1.html
3. http://blog.sina.com.cn/s/blog_4adc4b090101dtxp.html
332

被折叠的 条评论
为什么被折叠?



