大量程序表明,字符串操作是程序设计中最常见的操作。
String对象是不可变的,每一个看似修改了String值的方法,实际上都是创建了一个全新的String对象。
package com.chenxyt.java.practice;
public class Immutable {
public static String upCase(String s){
return s.toUpperCase();
}
public static void main(String[] args) {
String q = "howdy";
System.out.println(q);
String qq = upCase(q);
System.out.println(qq);
System.out.println(q);
}
}
运行结果:
String s = "abcde";
String x = Immutable.upCase(s);
因为方法的参数是用来传递信息的,而不是用来改变原有对象本身的。
package com.chenxyt.java.practice;
public class Concatetion {
public static void main(String[] args) {
String mango = "mango";
String s = "abc" + mango + "def" + 42;
System.out.println(s);
}
}
运行结果:
package com.chenxyt.java.practice;
import java.util.ArrayList;
import java.util.List;
public class InfiniteRecursion {
public String toString(){
return "InfiniteRecursion address" + this;
}
public static void main(String[] args) {
List v = new ArrayList();
for(int i = 0;i<10;i++){
v.add(new InfiniteRecursion());
}
System.out.println(v);
}
}
运行结果:
return "InfiniteRecursion address" + this;
时发生了类型转换,编译器发现“+”后边不是String类型,会试图转换成String类型,转换的方式就是调用toString方法,因此会递归调用,此处如果想正确打印地址,那么需要使用其基类Object的toString()方法。
所有的类都是Class类的对象,使用Class类的getMethods()方法可以返回该类的所有方法:
package com.chenxyt.java.practice;
import java.lang.reflect.Method;
public class StringMethods {
public static void main(String[] args) {
Class c = String.class;
Method[] methods = c.getMethods();
for(Method method :methods){
System.out.println(method);
}
}
}
运行结果:
public int java.lang.String.hashCode()
//比较两个字符串 重载了Object的方法 当两个字符串值相同、类型相同则认为相同 忽略了引用
public boolean java.lang.String.equals(java.lang.Object)
public java.lang.String java.lang.String.toString()
//获取指定索引下标位置上的字符
public char java.lang.String.charAt(int)
public int java.lang.String.codePointAt(int)
public int java.lang.String.codePointBefore(int)
public int java.lang.String.codePointCount(int,int)
public int java.lang.String.compareTo(java.lang.Object)
//按词典顺序比较两个字符串 大小写并不等价
public int java.lang.String.compareTo(java.lang.String)
public int java.lang.String.compareToIgnoreCase(java.lang.String)
//字符串连接 返回一个新的String为指定String连接参数
public java.lang.String java.lang.String.concat(java.lang.String)
//查找字符串中是否包含指定字符 存在返回true
public boolean java.lang.String.contains(java.lang.CharSequence)
//比较两个字符串
public boolean java.lang.String.contentEquals(java.lang.StringBuffer)
public boolean java.lang.String.contentEquals(java.lang.CharSequence)
public static java.lang.String java.lang.String.copyValueOf(char[])
public static java.lang.String java.lang.String.copyValueOf(char[],int,int)
public boolean java.lang.String.endsWith(java.lang.String)
//比较字符串是否相同 忽略大小写
public boolean java.lang.String.equalsIgnoreCase(java.lang.String)
public static java.lang.String java.lang.String.format(java.lang.String,java.lang.Object[])
public static java.lang.String java.lang.String.format(java.util.Locale,java.lang.String,java.lang.Object[])
public void java.lang.String.getBytes(int,int,byte[],int)
public byte[] java.lang.String.getBytes(java.lang.String) throws java.io.UnsupportedEncodingException
public byte[] java.lang.String.getBytes(java.nio.charset.Charset)
public byte[] java.lang.String.getBytes()
// s.getChars(1,2,char,3) 赋值s串中下标为1-2的到char中 char中起始位置为3
public void java.lang.String.getChars(int,int,char[],int)
public int java.lang.String.indexOf(int,int)
public int java.lang.String.indexOf(java.lang.String,int)
//是否包含该字符 包含返回下标 否则返回-1
public int java.lang.String.indexOf(java.lang.String)
public int java.lang.String.indexOf(int)
public native java.lang.String java.lang.String.intern()
public boolean java.lang.String.isEmpty()
public int java.lang.String.lastIndexOf(int,int)
public int java.lang.String.lastIndexOf(java.lang.String)
public int java.lang.String.lastIndexOf(java.lang.String,int)
public int java.lang.String.lastIndexOf(int)
//String 中字符的个数
public int java.lang.String.length()
public boolean java.lang.String.matches(java.lang.String)
public int java.lang.String.offsetByCodePoints(int,int)
public boolean java.lang.String.regionMatches(boolean,int,java.lang.String,int,int)
public boolean java.lang.String.regionMatches(int,java.lang.String,int,int)
//把字符串中的第一个参数字符替换成第二个
public java.lang.String java.lang.String.replace(char,char)
public java.lang.String java.lang.String.replace(java.lang.CharSequence,java.lang.CharSequence)
public java.lang.String java.lang.String.replaceAll(java.lang.String,java.lang.String)
public java.lang.String java.lang.String.replaceFirst(java.lang.String,java.lang.String)
public java.lang.String[] java.lang.String.split(java.lang.String,int)
public java.lang.String[] java.lang.String.split(java.lang.String)
public boolean java.lang.String.startsWith(java.lang.String,int)
//字符串起始串
public boolean java.lang.String.startsWith(java.lang.String)
public java.lang.CharSequence java.lang.String.subSequence(int,int)
//字符串截断
public java.lang.String java.lang.String.substring(int)
public java.lang.String java.lang.String.substring(int,int)
//返回一个字符数组,该字符数组包含字符串的所有字符
public char[] java.lang.String.toCharArray()
//字符串字符转换成小写
public java.lang.String java.lang.String.toLowerCase()
public java.lang.String java.lang.String.toLowerCase(java.util.Locale)
//字符串字符转换成大写
public java.lang.String java.lang.String.toUpperCase()
public java.lang.String java.lang.String.toUpperCase(java.util.Locale)
//删除String两端的空白字符
public java.lang.String java.lang.String.trim()
public static java.lang.String java.lang.String.valueOf(char)
public static java.lang.String java.lang.String.valueOf(float)
public static java.lang.String java.lang.String.valueOf(int)
public static java.lang.String java.lang.String.valueOf(long)
public static java.lang.String java.lang.String.valueOf(double)
public static java.lang.String java.lang.String.valueOf(java.lang.Object)
public static java.lang.String java.lang.String.valueOf(char[])
public static java.lang.String java.lang.String.valueOf(char[],int,int)
public static java.lang.String java.lang.String.valueOf(boolean)
public final native java.lang.Class java.lang.Object.getClass()
public final native void java.lang.Object.notify()
public final native void java.lang.Object.notifyAll()
public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException
public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException
public final void java.lang.Object.wait() throws java.lang.InterruptedException
注释了一些常用的方法,其它的方法可自行查阅。
package com.chenxyt.java.practice;
public class SimpleFormat {
public static void main(String[] args) {
int x = 5;
double y = 5.333221;
System.out.println("Row1: [" + x + " " + y + "]");
System.out.format("Row1: [%d %f]\n",x,y);
System.out.printf("Row1: [%d %f]\n",x,y);
}
}
运行结果:
package com.chenxyt.java.practice;
import java.io.PrintStream;
import java.util.Formatter;
public class Tutle {
private String name;
private Formatter f;
public Tutle(String name,Formatter f){
this.f = f;
this.name = name;
}
public void move(int x,int y){
f.format("%s The Tutle is at (%d,%d)\n",name,x,y);
}
public static void main(String[] args) {
Tutle tommy = new Tutle("Tommy",new Formatter(System.out));
Tutle terry = new Tutle("Terry",new Formatter(System.err));
tommy.move(0, 4);
terry.move(4, 8);
}
}
运行结果:
package com.chenxyt.java.practice;
import java.util.Formatter;
public class Reciept {
private double total = 0;
private Formatter f = new Formatter(System.out);
public void printTitle(){
f.format("%-15s %5s %10s\n","Item","Qty","Price");
f.format("%-15s %5s %10s\n","----","---","-----");
}
public void print(String name,int qty,double price){
f.format("%-15.15s %5d %10.2f\n",name,qty,price);
total+=price;
}
public void printTotal(){
f.format("%-15.15s %5s %10.2f\n","Tax","",total*0.06);
f.format("%-15.15s %5s %10s\n","","","------");
f.format("%-15.15s %5s %10.2f\n","Total","",total*1.06);
}
public static void main(String[] args) {
Reciept receipt = new Reciept();
receipt.printTitle();
receipt.print("Jack's Magic Beans",4,4.25);
receipt.print("Princess Beans",3,5.1);
receipt.print("Thres Bears Porridge",1,14.25);
receipt.printTotal();
}
}
运行结果:
package com.chenxyt.java.practice;
public class IntegerMatch {
public static void main(String[] args) {
System.out.println("-1234".matches("-?\\d+"));
System.out.println("5678".matches("-?\\d+"));
System.out.println("+911".matches("-?\\d+"));
System.out.println("+911".matches("(-|\\+)?\\d+"));
}
}
package com.chenxyt.java.practice; import java.util.Arrays; public class Splitting { public static String knights = "Then。when you have found the shrubbery.you must" + "cut down the mightiest tree in the forest。。。" + "with... a herring"; public static void split(String regex){ System.out.println(Arrays.toString(knights.split(regex))); } public static void main(String[] args) { split(" "); split("\\W+");
split("\\w+");
split("n\\W+"); } }
运行结果:
第一个是使用空格拆分,\\W表示非单词字符,\\w表示单词字符,第三个表示字母n以及后边的一个或多个非单词字符。可见与正则表达式相同的内容都消失了。
String类自带的最后一个正则表达式方法为替换,你可以替换正则表达式第一个匹配的子串,也可以替换所有匹配的地方。
package com.chenxyt.java.practice;
public class Replacing {
static String s = Splitting.knights;
public static void main(String[] args) {
System.out.println(s.replaceFirst("f\\w+","located"));
System.out.println(s.replaceAll("shrubbery|tree|herring","banana"));
}
}
package com.chenxyt.java.practice;
public class Rudolph {
public static void main(String[] args) {
for(String parten:new String[]{"Rudolph","[rR]udolph","[rR][aeiou][a-z]ol.*","R.*"}){
System.out.println("Rudolph".matches(parten));
}
}
}
package com.chenxyt.java.practice;
public interface CharSequence {
char charAt(int i );
int length();
String subSequence(int start,int end);
String toString();
}
package com.chenxyt.java.practice;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TestRegularExpression {
public static void main(String[] args) {
if(args.length<2){
System.out.println("Usage:\n java TestRegularExpression " + "characterSequence regularExpression+");
System.exit(0);
}
System.out.println("Input: \"" + args[0] + "\"");
for(String arg:args){
System.out.println("Regular expression: \"" + arg + "\"");
//编译正则表达式
Pattern p = Pattern.compile(arg);
//传入字符串进行匹配
Matcher m = p.matcher(args[0]);
while(m.find()){
System.out.println("Match \"" + m.group() + "\" at positions " + m.start() + "-" + (m.end() - 1));
}
}
}
}
package com.chenxyt.java.practice;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
public class SimpleRead {
public static BufferedReader input = new BufferedReader(new StringReader("Sir Robin of Camelot\n22 1.523222"));
public static void main(String[] args) {
try{
System.out.println("What's your name?");
String name = input.readLine();
System.out.println(name);
System.out.println("How old are you?What's your favorite double");
String numbers = input.readLine();
System.out.println(numbers);
String numArray[] = numbers.split(" ");
int age = Integer.parseInt(numArray[0]);
double favorite = Double.parseDouble(numArray[1]);
System.out.format("Hi %s.\n",name);
System.out.format("In 5 years you will be %d. \n",age+5);
System.out.format("My Favorite double is %f.",favorite/2);
}catch(IOException e){
System.err.println("I/O Exception");
}
}
}
package com.chenxyt.java.practice;
import java.util.Scanner;
public class BetterRead {
public static void main(String[] args) {
Scanner stdin = new Scanner(SimpleRead.input);
System.out.println("What's your name?");
String name = stdin.nextLine();
System.out.println(name);
System.out.println("How old are you?What's your favorite double");
System.out.println("(input:)");
int age = stdin.nextInt();
double favorite = stdin.nextDouble();
System.out.println(age);
System.out.println(favorite);
System.out.format("Hi %s.\n",name);
System.out.format("In 5 years you will be %d. \n",age+5);
System.out.format("My Favorite double is %f.",favorite/2);
}
}
package com.chenxyt.java.practice;
import java.util.Scanner;
public class ScannerDelimiter {
public static void main(String[] args) {
Scanner scanner = new Scanner("12,24 ,35,67");
scanner.useDelimiter("\\s*,\\s*");
while(scanner.hasNextInt()){
System.out.println(scanner.nextInt());
}
}
}
package com.chenxyt.java.practice;
import java.util.Scanner;
import java.util.regex.MatchResult;
public class ThreadAnalyzer {
static String threatData = "58.27.82.161@02/10/2005\n" +
"204.45.234.40@02/11/2005\n" +
"58.27.82.161@02/11/2005\n" +
"58.27.82.161@02/11/2005\n" +
"58.27.82.161@02/11/2005\n" +
"[Next log section width different data format]";
public static void main(String[] args) {
Scanner scanner = new Scanner(threatData);
String pattern = "(\\d+[.]\\d+[.]\\d+[.]\\d+)@" + "(\\d{2}/\\d{2}/\\d{4})";
while(scanner.hasNext(pattern)){
scanner.next(pattern);
MatchResult match = scanner.match();
String ip = match.group(1);
String date = match.group(2);
System.out.format("Thread on %s from %s\n",date,ip);
}
}
}
package com.chenxyt.java.practice;
import java.util.Arrays;
import java.util.Scanner;
import java.util.StringTokenizer;
public class ReplacingStringTokenizer {
public static void main(String[] args) {
String input = "But I'm not dead yet!I feel happy!";
StringTokenizer stoke = new StringTokenizer(input);
while(stoke.hasMoreElements()){
System.out.print(stoke.nextToken() + " ");
}
System.out.println();
System.out.println(Arrays.toString(input.split(" ")));
Scanner scanner = new Scanner(input);
while(scanner.hasNext()){
System.out.print(scanner.next() + " ");
}
}
}