第十三章 字符串

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. java实现二叉树常见操作

    package com.xk.test.struct.newp; import java.util.ArrayList; import java.util.LinkedList; import jav ...

  2. day 48

    目录 js BOM(浏览器对象模型) window对象 window子对象 弹出框 计时事件 DOM(文档对象模型) 查找标签 节点操作 事件 常用事件 绑定方式 jQuery jQuery介绍 jQ ...

  3. ASP.NET Core使用Quartz定时调度

    在应用程序开发过程中,经常会需要定时任务调度功能,本篇博客介绍Asp.net Core如何使用Quartz完成定时调度 一.Quartz使用步骤 创建调度器scheduler,并开启 创建Job作业 ...

  4. android studio学习----Failed to resolve: com.android.support:design:22.1.1

    这个目前好像没有合适的办法,唯一可行的就是 点击那个提示  进行SDK Manager下载就可以了 但是天朝的网啊,我试了很多次,突然的可以下载,运气啊 类似这一系列问题解决办法就是  重新更新SDK ...

  5. 面试题:java中String为什么要设置成final

    1.不可改变---执行效率高 2.因为String这个对象基本是被所有的类对象都会使用的到了,如果可以被复写,就会很乱套,比如map的key ,如果是一个string为key的话,String如果可以 ...

  6. java-log4j配置

    引入依赖: <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId ...

  7. InvalidOperationException: Operations that change non-concurrent collections must have exclusive access. A concurrent update was performed on this collection and corrupted its state. The collection's

    InvalidOperationException: Operations that change non-concurrent collections must have exclusive acc ...

  8. Django框架(十一)-- 补充:inclusion_tag、defer、only、choice、事务、创建多对多的第三张表、mvc和mtv模式

    一.inclusion_tag 1.作用 用于生成HTML片段,是数据由参数传入而变成动态 2.使用 # 1.app下新建一个模块,templatetags # 2.创建一个py文件(mytag.py ...

  9. 【Servlet】The servlets named [ByteServlet] and [content.ByteServlet] are both mapped to the url-pattern [ByteServlet] which is not permitted

    创建时间:6.30 The servlets named [ByteServlet] and [content.ByteServlet] are both mapped to the url-patt ...

  10. PAT 乙级 1039.到底买不买 C++/Java

    题目来源 小红想买些珠子做一串自己喜欢的珠串.卖珠子的摊主有很多串五颜六色的珠串,但是不肯把任何一串拆散了卖.于是小红要你帮忙判断一下,某串珠子里是否包含了全部自己想要的珠子?如果是,那么告诉她有多少 ...