String类

创建字符串对象

  • 用String类的构造方法创建字符串对象
    String s = new String("we are students");
  • 用一个已经创建好的字符串创建另一个字符串
    String s2 = new String(s);
  • 用一个字符数组a创建一个String对象
    char[] a = {'b','o','y'};
    String s = new String(a);
  • 提取字符数组a中的一部分字符创建一个String对象
    char[] a = {'s','t','b','u','s','n'};
    String s = new String(a,2,3);

常用方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
s1.length() //->int获取字符串的长度(char的个数) 
s1.equals(String s) //->boolean比较当前字符串对象的实体是否与参数指定的字符串s的实体相同
s1.startsWith(String s) //->boolean判断当前字符串对象的前缀是否是参数指定的字符串s
s1. endsWith(String s) //->boolean判断当前字符串对象的后缀是否是参数指定的字符串s
s1.compareTo(String s) //->int按字典序与参数s指定的字符串比较大小。
// 如果s1与s相同,该方法返回值0;
// 如果s1大于s,该方法返回正值;
// 如果s1小于s,该方法返回负值。
s1.indexOf(s2); //->int从当前字符串的头开始检索字符串s,并返回首次出现s的位置。
// 如果没有检索到字符串s,该方法返回的值是-1。
s1.substring(int startPoint) //获得一个当前字符串的子串,该子串是从当前字符串的startPoint处截取到最后所得到的字符串。
s.replaceAll(String s1, String s2)//->string 通过用参数s2指定的字符串替换原字符串s中由s1指定的所有字符串而得到的新的字符串s。
s.trim() //->string 去掉前后空格

//字符串与基本数据的相互转化
// string->num
public static int parseInt(String s)
public static byte parseByte(String s)
public static short parseShort(String s)
public static long parseLong(String s)
public static float parseFloat(String s)
public static double parseDouble(String s)
// num->string
public String valueOf(byte b)
public String valueOf(short s)
public String valueOf(int i)
public String valueOf(long l)
public String valueOf(float f)
public String valueOf(double d)

//example
public class Example6_2
{
public static void main(String args[])
{
System.out.println(Double.parseDouble("99.99"));

System.out.println(Integer.toBinaryString(64)); // or toString(64,2)
System.out.println(Integer.toOctalString(64)); // or toString(64,8)
System.out.println(Integer.toHexString(64)); // or toString(64,16)
}
}

tostring

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class TV 
{
String name;
double price;
TV(String name, double price)
{
this.name = name;
this.price = price;
}
}
class Student
{
String name;
double score;
Student(String name, double score)
{
this.name = name;
this.score = score;
}
public String toString() //
{
return name+": "+score;
}
}
import java.util.Date;
public class Example6_3
{
public static void main(String args[])
{
Date date = new Date();
Student stu = new Student("Tom", 89);
TV tv = new TV("Samsung", 8776);
System.out.println(date.toString()); //Sun Oct 19 18:29:48 CST 2014
System.out.println(stu.toString()); //Tom: 89.0
System.out.println(tv.toString()); //TV@52cd32e5
}
}

字符串与字符数组

char[] a = s.toCharArray();

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import java.util.Scanner; 

public class Example6_4
{
public static void main(String args[])
{
Scanner reader = new Scanner(System.in);
String s = reader.nextLine(); //abcdef
char[] a = s.toCharArray(); //转成字符数组!!!!!!!!
for(int i=0; i<a.length; i++) // a.length=6
{
a[i] = (char)(a[i]^'w'); //异或加密
}
String secret = new String(a);
System.out.println(secret); //》》》》

for(int i=0; i<a.length; i++)
{
a[i]=(char)(a[i]^'w'); //异或解密
}
String code = new String(a);
System.out.println(code); //abcdef
}
}

字符串与字节数组

1
2
3
4
5
6
7
8
9
10
public class Example6_5 
{
public static void main(String args[])
{
byte[] d = "ShenzhenUniversity".getBytes(); //string->byte[]
System.out.println(d.length);
String s = new String(d,8,10); //byte[]->string
System.out.println(s);
}
}

StringBuffer类

String类创建的字符串对象是不可修改的
StringBuffer类:能创建可修改的字符串序列.
该类的对象的实体的内存空间可以自动改变大小,便于存放一个可变的字符串。

  • length()方法获取实体中存放的字符序列的长度(length)
  • capacity()方法获取当前实体的实际容量(capacity)
  • append方法:可以将其它Java类型数据转化为字符串后,再追加到StringBuffer对象中。
  • char charAt(int index):得到参数index指定的位置上的单个字符。
    当前对象实体中的字符串序列的第一个位置为0,第二个位置为1,依次类推。
    index的值必须是非负的,并且小于当前对象实体中字符串序列的长度。
  • void setCharAt(int index, char ch):
    将当前StringBuffer对象实体中的字符串位置index处的字符用参数ch指定的字符替换。
    index的值必须是非负的,并且小于当前对象实体中字符串序列的长度。
  • StringBuffer insert(int index, String str):
    将一个字符串插入另一个字符串中,并返回当前对象的引用。
  • public StringBuffer reverse():
    将该对象实体中的字符串翻转,并返回当前对象的引用。
  • StringBuffer delete(int startIndex, int endIndex):
    从当前StringBuffer对象实体的字符串中删除一个子字符串,并返回当前对象的引用。
    要删除的子字符串下标从startIndex到endIndex-1。
  • StringBuffer replace(int startIndex, int endIndex, String str):
    将当前StringBuffer对象实体中的字符串的一个子字符串用参数str指定的字符串替换。
    从startIndex到endIndex-1的字符串被替换
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Example6_6 
{
public static void main(String args[])
{
StringBuffer str = new StringBuffer("0123456789");
str.setCharAt(0, 'a');
str.setCharAt(1, 'b');
System.out.println(str); //ab23456789

str.insert(2, "**");
System.out.println(str); //ab**23456789

str.delete(6,8);
System.out.println(str); //ab**236789
}
}

StringBuffer是线程安全的,StringBuilder不是线程安全的
• 线程安全是指多个线程操作同一个对象不会出现问题,即允许采用多线程的方式添加或删除字符。

StringTokenizer类

StringTokenizer(String s)
为字符串s构造一个分析器。
使用默认的分隔符集合,即空格符(多个空格被看做一个空格)、换行符’\n’、回车符’\r’、tab符’\t’、进纸符’\f’
StringTokenizer(String s, String delim)
为字符串s构造一个分析器,
参数delim中的字符被作为分隔符

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import java.util.*;  
public class Example6_7
{
public static void main(String args[])
{
String [] mess = {"integer part", "decimal part"};
Scanner reader = new Scanner(System.in); //99.9999
double x = reader.nextDouble();
String s = String.valueOf(x);
StringTokenizer st = new StringTokenizer(s,".");
for(int i=0; st.hasMoreTokens(); i++)
{
String str = st.nextToken();
System.out.println(mess[i] + ":" + str);
//integer part:99
//decimal part:9999
}
}
}

Scanner类

Scanner类不仅可以创建出用于读取用户从键盘输入的数据的对象,
而且还可以创建出用于解析字符串的对象。

以“空白”作为分隔符

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import java.util.*; 

public class Example_Scanner1
{
public static void main (String args[])
{
String cost = " TV cost 877 dollar, Computer cost 2398";
Scanner scanner = new Scanner(cost);
double sum = 0;
// 以“空白”作为分隔符
while(scanner.hasNext())
{
try{
double price = scanner.nextDouble();
sum = sum + price;
System.out.println(price); //877.0 2398.0
}
catch(InputMismatchException exp)
{
String t = scanner.next();
}
}
System.out.println("Sum: " + sum); //Sum: 3275.0
}
}

使用正则表达式作为分隔标记解析字符串

Scanner对象可以调用useDelimiter()方法将一个正则表达式作为分隔标记,
即和正则表达式匹配的字符串都是分隔标记。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import java.util.*; 
public class Example_Scanner2
{
public static void main (String args[])
{
String cost = "市话费: 176.89元, 长途费: 187.98元, 网络费: 928.66元";
Scanner scanner = new Scanner(cost);
scanner.useDelimiter("[^0123456789.]+"); //
while(scanner.hasNext())
{
try{
double price = scanner.nextDouble();
System.out.println(price); //176.89 187.98 928.66
}
catch(InputMismatchException exp)
{
String t = scanner.next();
}
}
}
}

模式匹配

(1) 建立模式对象
Pattern p = Pattern.compile("A\\d");
\d代表0到9中的任何一个
模式可以使用“|”位运算符进行逻辑“或”运算得到一个新模式。
pattern=pattern1|pattern2;
Pattern类调用静态方法compile(String pattern)来完成这一任务,
其中的参数pattern是一个正则表达式,称作模式对象使用的模式。
如果参数pattern指定的正则表达式有错,compile方法将抛出异常PatternSyntaxException。
(2) 建立匹配对象
模式对象p调用matcher(CharSequence input)方法返回一个Matcher对象m(称作匹配对象)
Matcher对象m有3个方法寻找参数input指定的字符序列中是否有和pattern匹配的子序列(pattern是创建模式对象p时使用的正则表达式)

  • public boolean find() :在input中寻找和pattern匹配的下一子序列
  • public boolean matches():判断input是否完全和pattern匹配
  • public boolean lookingAt():判断input的开始位置是否有和pattern匹配的子序列
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import java.util.regex.*; 

public class Example6_8
{
public static void main(String args[])
{
Pattern p; //模式对象
Matcher m; //匹配对象
String input = "0A1A2A3A4A5A6A7A8A9";
p = Pattern.compile("\\dA\\d"); //Pattern类调用静态方法compile(String pattern),参数pattern是一个正则表达式. "\\d"代表0到9中的任何一个
m = p.matcher(input); //模式对象p调用matcher(CharSequence input)方法返回一个Matcher对象m

while(m.find())
{
String str = m.group();
System.out.print("From " + m.start() + " To " + m.end() + ": ");
System.out.println(str);
}
// From 0 To 3: 0A1
// From 4 To 7: 2A3
// From 8 To 11: 4A5
// From 12 To 15: 6A7
// From 16 To 19: 8A9
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import java.util.regex.*; 

public class Example6_8
{
public static void main(String args[])
{
Pattern p;
Matcher m;
String input = "0A1A2A3A4A5A6A7A8A9";
p = Pattern.compile("\\dA\\d");
m = p.matcher(input);

String temp = m.replaceAll("***"); //将匹配的串替换成***
System.out.println(temp); //***A***A***A***A***
System.out.println(input); //0A1A2A3A4A5A6A7A8A9
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import java.util.regex.*; 
public class Example6_8
{
public static void main(String args[])
{
Pattern p;
Matcher m;
String input = "9A00A3";
p = Pattern.compile("\\dA\\d");
m = p.matcher(input);
if(!m.matches()) //判断input是否完全和pattern匹配
{
System.out.println("Not exact match");
}
if( m.lookingAt() ) //判断input的开始位置是否有和pattern匹配的子序列
{
String str = m.group();
System.out.println(str);
}
}
}

正则表达式及字符串的替换与分解

正则表达式

元字符

元字符 在正则表达式中的写法 意义
. . 代表任何一个字符。注:[.]表示点号。
\d \d 代表0~9的任何一个数字
\D \D 代表任何一个非数字字符
\s \s 代表空格类字符,‘\t’, ‘\n’, ‘\x0B’, ‘\f’, ‘\r’
\S \S 代表非空格类字符
\w \w 代表可用于标识符的字符(不包括美元符号)
\W \W 代表不能用于标识符的字符

限定修饰符

带限定符号的模式 意义
X? X出现0次或1次
X* X出现0次或多次
X+ X出现1次或多次
X{n} X恰好出现n次
X{n,} X至少出现n次
X{n, m} X出现n次至m次

// example

  • pattern = “A[1359]?”
    “A”, “A1”, “A3”, “A5”, “A9 ”
  • pattern = “@\w{4}”
    “@abcd”, “@girl”, “@moon”, “@flag ”

其他

  • 在正则表达式(模式)中可以使用一对方括号括起若干个字符,代表方括号中的任何一个字符
    pattern = "[159]ABC"
    “1ABC” 、“5ABC”和“9ABC”
  • [abc]
    代表a, b, c中的任何一个
  • [^abc]
    代表除了a, b, c以外的任何字符
  • [a-d]
    代表a至d中的任何一个
  • 方括号里嵌套方括号
    • [a-d[m-p]]:代表a至d,或m至p中的任何字符(并)
    • [a-z&&[def]]:代表d, e或f中的任何一个(交)
    • [a-f&&[^bc]]:代表a, d, e, f(差)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import java.util.regex.*; 
public class Example6_10
{
public static void main(String args[])
{
Pattern p;
Matcher m;
String s1 = "likeKFChateMDlike123jkjhate999like888";
p = Pattern.compile("like\\w{3}|hate\\w{2}"); //使用或“|"
m = p.matcher(s1);
while(m.find())
{
String str = m.group();
System.out.print("From " + m.start() + " To " + m.end() + ": ");
System.out.println(str);
}
}
}

字符串的替换

String result = "12hello567".replaceAll("[a-zA-Z]+","***");
//12***567
1
2
3
4
5
6
7
8
9
10
11
12
public class Example_replaceAll 
{
public static void main (String args[])
{
String str = "Please logon :http://www.cctv.cn Watch TV";
String regex = "(http://|www)[.]?\\w+[.]{1}\\w+[.]{1}\\p{Alpha}+"; //\\p{Alpha}表示字母字符

String newStr = str.replaceAll(regex,"");
System.out.println(str);
System.out.println(newStr);
}
}

字符串的分解

public String[] split(String regex)
使用参数指定的正则表达式regex作为分隔标记分解出其中的单词,
并将分解出的单词存放在字符串数组中
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import java.util.Scanner;  
public class Example6_11
{
public static void main (String args[])
{
Scanner reader = new Scanner(System.in);
String str = reader.nextLine();
//空格字符、数字和符号(!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~)组成的正则表达式
String regex = "[\\s\\d\\p{Punct}]+"; //\\p{Punct}表示标点符号 !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
String[] words = str.split(regex);
for(int i=0; i<words.length; i++)
{
int m = i+1;
System.out.println("Word" + m + ":" + words[i]);
}
}
}