第十三章 字符串

13.1 不可变String

String对象是不可变的。String类中每一个看起来会修改String值得方法,实际上都是创建了一个全新得String对象,以包含修改后得字符串内容。

13.2 无意识得递归

Java中每个类从根本上都是继承自Object,标准容器类自然也不例外。

使用toString()方法打印出对象得内存地址

import java.util.ArrayList;
import java.util.List; public class InfiniteRecursion
{
public static void main(String[] args)
{
List<AAA> v = new ArrayList<AAA>();
for (int i = 0; i < 10; i++)
v.add(new AAA());
System.out.println(v);
}
}
class AAA
{
public String toString()
{
return " InfiniteRecursion address: " + super.toString() + "\n";
}
}

13.3 格式化输出

printf("Row 1:[%d %f]\n",x,y);

占位符称作格式修饰符,它们说明了插入数据的位置,还说明了插入数据的类型。

format()与printf()是等价的。

13.3.3 Formatter类

当你创建一个Formatter对象的时候,需要向其构造器传递一些信息,告诉它最终结果在哪里输出。

import java.io.PrintStream;
import java.util.Formatter; public class Turtle
{
private String name;
private Formatter f;
public Turtle(String name, Formatter f) {
this.name = name;
this.f = f;
}
public void move(int x, int y) {
f.format("%s The Turtle is at (%d,%d)\n", name, x, y);
}
public static void main(String[] args) {
PrintStream outAlias = System.err;
Turtle tommy = new Turtle("Tommy",
new Formatter(System.err));
Turtle terry = new Turtle("Terry",
new Formatter(outAlias));
tommy.move(0,0);
terry.move(4,8);
tommy.move(3,4);
terry.move(2,5);
tommy.move(3,3);
terry.move(3,3);
}
}

Formatter的构造器经过重载可以接受多种输出目的地,最常用的还是PrintString(),OutputStream和File。

13.3.4 格式化说明符

%[argument_index$][flags][width][.precision]conversion

width用来控制一个域的最小尺寸。默认下,数据是右对齐,不过可以通过使用“-”标志来改变对齐方向。

precision指示最大大小。用于string表示字符最大数量,用于浮点表示小数部分要显示出来的位数,不可用于整数。

import java.util.*;
public class Receipt
{
private static final int width=15;
private double total = 0;
private Formatter f = new Formatter(System.out);
public void printTitle() {
f.format("%-"+width+"s %"+(width-10)+"s %"+(width-5)+"s\n", "Item", "Qty", "Price");
f.format("%-"+width+"s %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("%-15s %5s %"+(width-5)+".2f\n", "Tax", "", total*0.06);
f.format("%-15s %5s %10s\n", "", "", "-----");
f.format("%-15s %5s %10.2f\n", "Total", "",
total * 1.06);
}
public static void main(String[] args) {
Receipt receipt = new Receipt();
receipt.printTitle();
receipt.print("Jack's Magic Beans", 4, 4.25);
receipt.print("Princess Peas", 3, 5.1);
receipt.print("Three Bears Porridge", 1, 14.29);
receipt.printTotal();
}
}

13.3.5 Formatter转换

import java.math.*;
import java.util.*;
public class Conversion
{
public static void main(String[] args) {
Formatter f = new Formatter(System.out); char u = 'a';
System.out.printf("%3s : %s\n","u","a");
System.out.println("u = 'a'");
f.format("s: %s\n", u);
// f.format("d: %d\n", u);
f.format("c: %c\n", u);
f.format("b: %b\n", u);
// f.format("f: %f\n", u);
// f.format("e: %e\n", u);
// f.format("x: %x\n", u);
f.format("h: %h\n", u); int v = 121;
System.out.println("v = 121");
f.format("d: %d\n", v);
f.format("c: %c\n", v);
f.format("b: %b\n", v);
f.format("s: %s\n", v);
// f.format("f: %f\n", v);
// f.format("e: %e\n", v);
f.format("x: %x\n", v);
f.format("h: %h\n", v); BigInteger w = new BigInteger("50000000000000");
System.out.println(
"w = new BigInteger(\"50000000000000\")");
f.format("d: %d\n", w);
// f.format("c: %c\n", w);
f.format("b: %b\n", w);
f.format("s: %s\n", w);
// f.format("f: %f\n", w);
// f.format("e: %e\n", w);
f.format("x: %x\n", w);
f.format("h: %h\n", w); double x = 179.543;
System.out.println("x = 179.543");
// f.format("d: %d\n", x);
// f.format("c: %c\n", x);
f.format("b: %b\n", x);
f.format("s: %s\n", x);
f.format("f: %f\n", x);
f.format("e: %e\n", x);
// f.format("x: %x\n", x);
f.format("h: %h\n", x); Conversion y = new Conversion();
System.out.println("y = new Conversion()");
// f.format("d: %d\n", y);
// f.format("c: %c\n", y);
f.format("b: %b\n", y);
f.format("s: %s\n", y);
// f.format("f: %f\n", y);
// f.format("e: %e\n", y);
// f.format("x: %x\n", y);
f.format("h: %h\n", y); boolean z = false;
System.out.println("z = false");
// f.format("d: %d\n", z);
// f.format("c: %c\n", z);
f.format("b: %b\n", z);
f.format("s: %s\n", z);
// f.format("f: %f\n", z);
// f.format("e: %e\n", z);
// f.format("x: %x\n", z);
f.format("h: %h\n", z);
}
}

13.3.6 string.format()

String.format()是一个static方法,它接受与Formatter.format()方法一样的参数,但返回一个String对象。

public class DatabaseException extends Exception
{
public DatabaseException(int transactionID, int queryID,
String message) {
super(String.format("(t%d, q%d) %s", transactionID,
queryID, message));
}
public static void main(String[] args) {
try {
throw new DatabaseException(3, 7, "Write failed");
} catch(Exception e) {
System.out.println(e);
}
}
}

String.format()内部也是创建了一个Formatter对象,然后将传入的参数转给Formatter。

13.6 正则表达式

正则表达式提供一种完全通用的方式,来解决字符串匹配,选择,编辑和验证。

13.6.1 基础

使用split()方法分割字符串:

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(" "); // Doesn't have to contain regex chars
split("\\W+"); // Non-word characters
split("n\\W+"); // 'n' followed by non-word characters
QA7.getString();
QA7.E9();
}
}

使用String自带的正则表达式工具替换:

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"));
}
}

13.6.2 创建正则表达式

下面每一个表达式都能匹配字符串"Rudolph":

public class Rudolph {
public static void main(String[] args) {
for (String pattern : new String[] { "Rudolph", "[rR]udolph", "[rR][aeiou][a-z]ol.*", "R.*" })
System.out.println("Rudolph".matches(pattern));
}
}

我们的目的并不是编写最难理解的正则表达式,而是尽量编写能够完成任务的最简单的最必要的正则表达式。

13.6.3 量词

量词描述了一个模式吸收输入文本的方式:

  • 贪婪型:
  • 勉强型:
  • 占有型:

13.6.4 Pattern和Matcher

用static Pattern.compile()方法来编译正则表达式,它会根据String类型的正则表达式生成一个Pattern对象,把你要检索的字符串传入Pattern对象的matcher()方法。matcher()方法会生成一个Matcher对象。

测试正则表达式,看它们是否匹配一个输入字符串:


find()

Matcher.find()方法可用来查找多个匹配:


组是用括号划分的正则表达式,可以根据组的编号来引用某个组。组号为0表示整个表达式,组号为1表达被一对括号括起的组。


start()与end()

在匹配操作成功后,start()返回先前匹配的其实位置的索引,而end()返回所匹配的最后字符的索引加一的值。


Pattern标记

Pattern类的compile()方法还有一个版本,它接受一个参数,以调整匹配行为:

Pattern Pattern.compile(String regex,int flag)

通过"或"操作符组合多个标记功能:


13.6.5 Split()

Split()方法将输入字符串断开成字符串对象数组。

按照通用边界断开文本:


13.6.6 替换操作

正则表达式特别便于替换文本。


13.6.7 reset()

通过reset()方法,将现有的Matcher对象应用于一个新的字符串序列:


13.6.8 正则表达式与Java I/O

输出的是有匹配的部分以及匹配部分在行中的位置:


17.7 扫描输入

使用Scanner类扫描输入:


13.7.1 Scanner定界符

用正则表达式指定自己所需的定界符:


13.7.2 用正则表达式扫描


Java基础之十三 字符串的更多相关文章

  1. Java基础-处理json字符串解析案例

    Java基础-处理json字符串解析案例 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 作为一名开发人员,想必大家或多或少都有接触到XML文件,XML全称为“extensible ...

  2. 夯实Java基础(十三)——字符串

    字符串应该是我们在Java中用的最频繁.最多的,可见字符串对于我们来说是多么的重要,所以我们非常有必要去深入的了解一下. 1.String String就代表字符串,在Java中字符串属于对象.我们刚 ...

  3. 【java基础学习】字符串

    字符串 1. java内存区域(堆区.栈区.常量池) 2. String方法 获取长度 length(); 获取位置 indexOf(index); lastIndexOf(index) 获取子串 c ...

  4. java 基础知识六 字符串1

    java  基础知识六  字符串1 String 不是java的基本数据类型 String 不是java的基本数据类型 String 不是java的基本数据类型 字符串是是一个字符序列 1.创建 创建 ...

  5. Java基础语法<二> 字符串String

    1. 代码点与代码单元 Java字符串由char序列组成.大多数的常用Unicode字符使用一个代码单元就可以表示,而辅助字符需要一对代码单元表示. length()方法将返回采用UTF-16编码表示 ...

  6. java基础18 String字符串和Object类(以及“equals” 和 “==”的解析)

    一.String字符串 问:笔试题:new String("abc")创建了几个对象?答:两个对象,一个对象是 位于堆内存,一个对象位于字符串常量池 class Demo17 { ...

  7. Java基础(十三)反射

    一.反射 1.反射概念 JAVA反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法:对于任意一个对象,都能够调用它的任意一个方法和属性:这种动态获取的信息以及动态调用对象的方法的 ...

  8. java基础第十三篇之Collection

    常见的几种数据结构: * 1.堆栈:先进后出 * 2.队列:先进先出 * 3.数组:查找快,增删慢 * 4.链表:查找慢,增删快  import java.util.LinkedList; /* * ...

  9. Java基础学习【字符串倒序输出+排序】

    字符串逆序输出 import java.util.*; public class Main{ public static void main(String [] args) { //字符串逆序输出 S ...

随机推荐

  1. 练手WPF(一)——模拟时钟与数字时钟的制作(上)

    一.Visual Studio创建一个WPF项目. 简单调整一下MainWindow.xaml文件.主要使用了两个Canvas控件,分别用于显示模拟和数字时钟,命名为AnalogCanvas.digi ...

  2. c# 合并两个DataTable

    当两个DataTable 结构相同可以用自带方法(Merge)合并 // // 摘要: // 将指定的 System.Data.DataTable 与当前的 DataTable 合并,指示是否在当前的 ...

  3. .NET CORE 控制台应用程序配置log4net日志文件

    使用文件格式记录日志 1.新建一个.NET CORE控制台应用程序,添加log4net.dll引用,打开工具->NuGet包管理器->管理解决方案的NuGet程序包. 2.在NuGet-解 ...

  4. Java之路---Day17(数据结构)

    2019-11-04-23:03:13 目录: 1.常用的数据结构 2.栈 3.队列 4.数组 5.链表 6.红黑树 常用的数据结构: 包含:栈.队列.数组.链表和红黑树 栈: 栈:stack,又称堆 ...

  5. java--Date时间

    Date: 表示特定的瞬间,精确到毫秒,通过方法设定自己所表示的时间,可以表示任意的时间 System.currentTimeMillis() :返回的当前系统时间, 1970-1-1 至今的毫秒数 ...

  6. SPring boot jpa 封装查询条件

    最近使用spring data jpa做了两个项目,对于动态查询的不友好做了个类似hibernate的封装,记录也分享下 首先定义一个所有条件的容器,继承Specification /** * 定义一 ...

  7. 『计算机视觉』imgaug图像增强库中部分API简介

    https://github.com/aleju/imgaug 介绍一下官方demo中用到的几个变换,工程README.md已经给出了API简介,个人觉得不好理解,特此单独记录一下: import n ...

  8. Mysql数据库之调整最大连接数

    .查看最大连接数 show variables like '%max_connections%'; 2.修改最大连接数 set GLOBAL max_connections = 200; 以下的文章主 ...

  9. linux 以导入文件形式添加定时任务(crontab)时需要注意的坑

    在实际操作过程中发现,使用导入文件形式添加定时任务时,会将用户已有的定时任务全部覆盖清理(先清空,再重新导入),所以在使用文件导入定时任务时,需要先将已有定时任务导出,然后将新任务进行追加到已有定时任 ...

  10. JanusGraph入门,schema及数据模型

    5.Schema和数据建模 每个JanusGraph都有一个schema,该schema由edge labels,property keys,和vertex组成.JanusGraph schema可以 ...