第十三章 字符串

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. spring好文章整理

    彻底搞明白Spring中的自动装配和Autowired IDEA编译spring 5源码 Spring源码——IDEA读Spring源码环境搭建 导入spring源码org.springframewo ...

  2. 2019-11-29-WPF-如何在绑定失败异常

    原文:2019-11-29-WPF-如何在绑定失败异常 title author date CreateTime categories WPF 如何在绑定失败异常 lindexi 2019-11-29 ...

  3. mini Redis(项目 二)

    一个仿Redis的内存数据库(主要用来做命令解析)服务端,  客户端使用的开源工具 : https://dom4j.github.io/     github:https://github.com/h ...

  4. 后台数据转换成Excel,前台下载

    <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactI ...

  5. 简单实现Shiro单点登录(自定义Token令牌)

    1. MVC Controller 映射 sso 方法. /** * 单点登录(如已经登录,则直接跳转) * @param userCode 登录用户编码 * @param token 登录令牌,令牌 ...

  6. Sharding-Jdbc概念与使用技巧

    1. Sharding-Jdbc概念与使用技巧 此讲解版本为4.0.0-RC1,目前最新的版本 2019年5月21日发布 1.1. 绑定表 指分片规则一致的主表和子表.例如:t_order表和t_or ...

  7. 记录下vue keep-alive IOS下无法保存滚动scroll位置的问题

    最近 做的项目,遇到了一点小麻烦,就是我一个页面A页面是加载 列表数据 ,B页面是展示详细信息的.A进去B时,缓存A页面. 效果 做出来 后,缓存是缓存数据 了,但是当我A页面的列表数据 好多,要滚动 ...

  8. MySQL单表数据不要超过500万行:是经验数值,还是黄金铁律?

    本文阅读时间大约3分钟. 梁桂钊 | 作者 今天,探讨一个有趣的话题:MySQL 单表数据达到多少时才需要考虑分库分表?有人说 2000 万行,也有人说 500 万行.那么,你觉得这个数值多少才合适呢 ...

  9. CentOS6安装部署配置Nginx

    操作系统: CentOS 6.9 脚本语言: shell https://github.com/iscongyang/Practical/blob/master/shell-scripts/insta ...

  10. php-fpm编译安装脚本

      PHP是开源.轻量级.高效的开发语言,特别适合web项目开发,在中小型互联网公司中常用于开发web后端.PHP常与Nginx及MySQL数据库结合,搭建LNMP环境.以下为centos7系统下ph ...