Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(十三)之Strings
Immutable Strings
Objects of the String class are immutable.
If you examine the JDK documentation for the String class, you’ll see that every method in the class that appears to modify a String actually creates and returns a brand new String object containing the modification. The original String is left untouched.
Overloading '+' vs. StringBuilder
Immutability can have efficiency issues. A case in point is the operator ‘+’ that has been overloaded for String objects.
String s = "abc" + mango + "def" + 47; // like: "abc".append(mango).append("def").append(47);
The String "abc" could have a method append( ) that creates a new String object containing "abc" concatenated with the contents of mango. The new String object would then create another new String that added "def," and so on.
This would certainly work, but it requires the creation of a lot of String objects just to put together this new String, and then you have a bunch of intermediate String objects that need to be garbage collected.
Decompile: javap -c ClassName
-c flag will produce the JVM bytecodes
If you try to take shortcuts and do something like append(a + ": " + c), the compiler will jump in and start making more StringBuilder objects again.
StringBuilder was introduced in Java SE5. Prior to this, Java used StringBuffer, which ensured thread safety (see the Concurrency chapter) and so was significantly more expensive.
Unintended recursion
Suppose you’d like your toString( ) to print the address of your class. It seems to make sense to simply refer to this:
public String toString() {
return " InfiniteRecursion address: " + this + "\n"; // 调用,实际上就是调用this.toString() 会导致死循环调用
}
解决方案:
this -> super.toString();
Operations on Strings
只罗列部分方法
| Method | Arguments,Overloading | Use |
| Constructor() |
Overloading:default,String,StringBuilder, StringBuffer,char arrays,byte arrays |
Creating String objects |
| getChars(),getBytes() | ... | Copy chars or bytes into an external array |
| toCharArray() | ||
| compareTo() | 比较大小,区分大小写 | |
| contains() | A CharSequence to search for | |
| contentEquals() | A CharSequence or StringBuffer to compare to | |
| regionMatches() |
Offset into this String, the other String and its offset and length to compare. Overload adds "ignore case." |
|
| startsWith() |
String that is might start with. Overload adds offset into argument |
|
| valueOf() | Overloaded: Object, char[],char[] and offset and count,boolean,char,int,long,float,double | |
| intern() | Produces one and only one String reference per unique character sequence |
Formatting output
System.out.format()
Java SE5 introduced the format() method, available to PrintStream or PrintWriter object.
System.out.println("Row 1: [" + x + " " + y + "]"); // The old way
System.out.format("Row 1: [%d %f]\n", x,y); // The new way
The Formatter class
All of Java's new formatting functionality is handled by the Formatter class in the java.util package.
When you create a Formatter object, you tell it where you want this result to go by passing that information to the constructor.
The constructor is overloaded to take a range of output locatins, but the most useful are PrintStreams, OutputStreams, and Files.
Format specifiers
general syntax: %[argument_index$][flags][width][.precision]conversion
width: control the minimun size of a filed. if necessary padding it with spaces
flags "-": By default, the date is right justified, but this can be overridden by including a "-" in the flags section
precision: specify a maximum
1. For Strings, specifies the maximum number of characters from the String to print.
2. For floating point numbers, specifies the number of decimal places to display ( the default is 6), rounding if there are too many of adding trailing zeros if there are too few.
3. Not for integers
Formatter conversions
d: Integral (as decimal 十进制)
c: Unicode character
b: Boolean value
s: String
f: Floating point(as decimal)
e: Floating point ( in scientific notation)
x: Integral (as hex)
h: Hash code (as hex)
%: Literal "%"
Notice that the ‘b’ conversion works for each variable above. Although it’s valid for any argument type, it might not behave as you’d expect. For boolean primitives or Boolean objects, the result will be true or false, accordingly. However, for any other argument, as long as the argument type is not null the result is always true. Even the numeric value of zero, which is synonymous with false in many languages (including C), will produce true, so be careful when using this conversion with non-boolean types.
String.format()
String.format( ) is a static method which takes all the same arguments as Formatter’s format( ) but returns a String.
result.append(String.format("%05X: ", n)); // 长度为5,不够的前面补零
Regular expressions
Basic
In Java, ‘ \ \ ‘ means "I’m inserting a regular expression backslash, so that the following character has special meaning." For example, if you want to indicate a digit, your regular expression string will be ‘\\d’. If you want to insert a literal backslash, you say ‘\\\\’- However, things like newlines and tabs just use a single backslash: ‘\n\t’.
To indicate "one or more of the preceding expression," you use a ‘+’.
In regular expressions, parentheses have the effect of grouping an expression, and the vertical bar ‘|’ means OR. So (-|\\+)?
(-|\\+)? means that this part of the string may be either a ‘-’ or a ‘+’ or nothing (because of the ‘?’).
Because the ‘+’ character has special meaning in regular expressions, it must be escaped with a ‘\\’ in order to appear as an ordinary character in the expression.
‘\W’, which means a non-word character (the lowercase version, ‘\w’, means a word character)
spilt()
replaceFirst()
replaceAll()
You'll see that the non-String regular expressions have more powerful replacement tools. Non-String regular expressions are also significantly more efficient if you need to use the regular expression more than once.
Create regular expressions
A complete list of constructs for building regular expressions can be found in the JDK documentation for the Pattern class for package java.util.regex




Quantifiers (??)
•Greedy: Quantifiers are greedy unless otherwise altered. A greedy expression finds as many possible matches for the pattern as possible. A typical cause of problems is to assume that your pattern will only match the first possible group of characters, when it’s actually greedy and will keep going until it’s matched the largest possible string.
•Reluctant: Specified with a question mark, this quantifier matches the minimum number of characters necessary to satisfy the pattern. Also called lazy, minimal matching, non-greedy, or ungreedy.
•Possessive: Currently this is only available in Java (not in other languages) and is more advanced, so you probably won’t use it right away. As a regular expression is applied to a string, it generates many states so that it can backtrack if the match fails. Possessive quantifiers do not keep those intermediate states, and thus prevent backtracking. They can be used to prevent a regular expression from running away and also to make it execute more efficiently.

CharSequence
The interface called CharSequence establishes a generalized definition of a character sequence abstracted from the CharBuffer, String, StringBuffer, or StringBuilder classes
Many regular expression operations take CharSequence arguments.
Pattern and Matcher
In general, you’ll compile regular expression objects rather than using the fairly limited String utilities. To do this, you import java.util.regex, then compile a regular expression by using the static Pattern.compile( ) method. This produces a Pattern object based on its String argument. You use the Pattern by calling the matcher( ) method, passing the string that you want to search. The matcher( ) method produces a Matcher object, which has a set of operations to choose from
Pattern p = Pattern.compile(arg);
Matcher m = p.matcher(args[0]);
while(m.find()){}
static boolean matches(String regex, CharSequence input)
boolean matches()
boolean lookingAt()
boolean find()
boolean find(int start)
find()
public class Finding {
public static void main(String[] args) {
Matcher m = Pattern.compile("\\w+")
.matcher("Evening is full of the linnet’s wings");
while(m.find())
printnb(m.group() + " ");
print();
int i = 0;
while(m.find(i)) {
printnb(m.group() + " ");
i++;
}
}
} /* Output:
Evening is full of the linnet s wings
Evening vening ening ning ing ng g is is s full full ull ll l of of f the the he e linnet linnet innet nnet net et t s s wings wings ings ngs gs s
*/
Groups
Groups are regular expressions set off by parentheses that can be called up late with their group number. Group 0 indicates the whole expression match, group 1 is the first parethesized group
A(B(C))D : Group 0 is ABCD, group 1 is BC, and group2 is C.
The Matcher object has methods to give you information about groups:
public int groupcount()--returns the number of groups in this matcher's pattern. Group 0 is not included in this count
public String group()--returns group 0 from the previous match operation
public String group(int i )--returns the given group number during the previous match operation. If the match was successful, but the group specified failed to match any part of the input string, then null is returned
public int start(int group) returns the start index of the group found in the previous match opetation
public int end(int group) returns the index of the last character, plus one, of the group found in the previous operation
the normal behavior is to match "$" with the end of the entire input sequence, so you must explicitly tell the regular expression to pay attention to newlines with the input. This is accomplished with the '(?m)' pattern flag at the beginning of the sequence
start() and end()
Following a successful matching operation, start( ) returns the start index of the previous match, and end( ) returns the index of the last character matched, plus one. Invoking either start( ) or end( ) following an unsuccessful matching operation (or before attempting a matching operation) produces an IllegalStateException.
Notice that find( ) will locate the regular expression anywhere in the input, but lookingAt( ) and matches( ) only succeed if the regular expression starts matching at the very beginning of the input. While matches( ) only succeeds if the entire input matches the regular expression, lookingAt( ) succeeds if only the first part of the input matches.
Pattern flags
Pattern Pattern.compile(String regex, int flag)
Pattern.compile("(?m)(\\S+)\\s+((\\S+)\\s+(\\S+))$") 等价于
Pattern.compile("(\\S+)\\s+((\\S+)\\s+(\\S+))$",Pattern.MULTILINE)
Note that the behavior of most of the flags can also be obtained by inserting the parenthesized characters into your regular expression preceding the place where you want the mode to take effect.
常用的:Pattern.CAST_INSENSITIVE (?i)
Pattern.COMMENTS (?x) -- In this mode, whitespace is ignored, and embedded comments starting with # are ignored until the end of a line. Unix lines mode can also be enabled via the embedded flag expression.
Pattern.MULTILINE (?m) -- In multiline mode, the expressions ‘^’ and ‘$’ match the beginning and ending of a line, respectively.’^’ also matches the beginning of the input string, and ‘$’ also matches the end of the input string. By default, these expressions only match at the beginning and the end of the entire input string.
split()
String[] split(CharSequence input)
String[] split(CharSequence input, int limit); // limits the number of splits that occur
Replace operations
replaceFirst(String replacement)
replaceAll(String replacement)
appendReplacement(StringBuffer sbuf,String replacement)
appendTail(StringBuffer sbuf, String replacement)
/*! Here’s a block of text to use as input to
the regular expression matcher. Note that we’ll
first extract the block of text by looking for
the special delimiters, then process the
extracted block. !*/
public class TheReplacements {
public static void main(String[] args) throws Exception {
String s = TextFile.read("TheReplacements.java");
// Match the specially commented block of text above:
Matcher mInput =
Pattern.compile("/\\*!(.*)!\\*/", Pattern.DOTALL) // 默认情况, "." 不匹配行终结符,在dotall模式下,匹配所有字符
.matcher(s);
if(mInput.find())
s = mInput.group(1); // Captured by parentheses
// Replace two or more spaces with a single space:
s = s.replaceAll(" {2,}", " ");
// Replace one or more spaces at the beginning of each
// line with no spaces. Must enable MULTILINE mode:
s = s.replaceAll("(?m)^ +", "");
print(s);
s = s.replaceFirst("[aeiou]", "(VOWEL1)");
StringBuffer sbuf = new StringBuffer();
Pattern p = Pattern.compile("[aeiou]");
Matcher m = p.matcher(s);
// Process the find information as you perform the replacements;
while(m.find())
m.appendReplacement(sbuf, m.group().toUpperCase());
// Put in the remainder of the text:
m.appendTail(sbuf);
print(sbuf);
}
} /* Output:
Here’s a block of text to use as input to
the regular expression matcher. Note that we’ll
first extract the block of text by looking for
the special delimiters, then process the
extracted block.
H(VOWEL1)rE’s A blOck Of tExt tO UsE As InpUt tO
thE rEgUlAr ExprEssIOn mAtchEr. NOtE thAt wE’ll
fIrst ExtrAct thE blOck Of tExt by lOOkIng fOr
thE spEcIAl dElImItErs, thEn prOcEss thE
ExtrActEd blOck.
*///:~
These two replacements are performed with the equivalent (but more convenient, in this case) replaceAll( ) that’s part of String. Note that since each replacement is only used once in the program, there’s no extra cost to doing it this way rather than precompiling it as a Pattern.
reset()
An existing Matcher object can be applied to a new character sequence using the reset() methods
m.reset("fix the rig with rags");
m.reset() set the Matcher to the beginning of the current sequence.
Regular expressions and Java I/O
深入学习正则表达式,可以参考Mastering Regular Expressions, 2nd Edition, by Jeffrey E.F.Friedl (O‘Reilly, 2002)
Scanning input
StringReader turns a String into a readable stream
Scanner constructor can take just about any kind of input object, including a File object, an InputStream, a String and a Readable
With Scanner, the input, tokenizing, and parsing are all ensconced in various different kinds of "next" methods. A plain next( ) returns the next String token, and there are "next" methods for all the primitive types (except char) as well as for BigDecimal and Biglnteger.
There are also corresponding "hasNext" methods that return true if the next input token is of the correct type.
the most recent exception is available through the ioException( ) method, so you are able to examine it if necessary. (??)
Scanner delimiters
By default, a Scanner splits input tokens along whitespace, but you can also specify your own delimiter pattern in the form of a regular expression
scanner.useDelimiter("\\s*,\\s*");
delimiter() return the current Pattern being used as a delimiter
Scanning with regular expressions
In addition to scanning for predefined primitive types, you can also scan for your own userdefined patterns
public class ThreatAnalyzer {
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/12/2005\n" +
"58.27.82.161@02/12/2005\n" +
"[Next log section with 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("Threat on %s from %s\n", date,ip);
}
}
} /* Output:
Threat on 02/10/2005 from 58.27.82.161
Threat on 02/11/2005 from 204.45.234.40
Threat on 02/11/2005 from 58.27.82.161
Threat on 02/12/2005 from 58.27.82.161
Threat on 02/12/2005 from 58.27.82.161
*///:~
There's one caveat when scanning with regular expressions. The pattern is matched against the next input token only, so if your pattern contains a delimiter it will never be matched
StringTokenizer
Before regular expressions or the Scanner class, the way to split a string into parts was to "tokenize" it with StringTokenize
Summary
you must sometimes pay attention to efficiency detail such as the appropriate use of StringBuilder
Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(十三)之Strings的更多相关文章
- Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(七)之Access Control
Access control ( or implementation hiding) is about "not getting it right the first time." ...
- Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(六)之Initialization & Cleanup
Two of these safety issues are initialization and cleanup. initialization -> bug cleanup -> ru ...
- Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(二)之Introduction to Objects
The genesis of the computer revolution was a machine. The genesis of out programming languages thus ...
- Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(十四)之Type Information
Runtime type information (RTTI) allow you to discover and use type information while a program is ru ...
- Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(十二)之Error Handling with Exceptions
The ideal time to catch an error is at compile time, before you even try to run the program. However ...
- Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(十一)之Holding Your Objects
To solve the general programming problem, you need to create any number of objects, anytime, anywher ...
- Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(十)之Inner Classes
The inner class is a valuable feature because it allows you to group classes that logically belong t ...
- Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(九)之Interfaces
Interfaces and abstract classes provide more structured way to separate interface from implementatio ...
- Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(八)之Polymorphism
Polymorphism is the third essential feature of an object-oriented programming language,after data ab ...
随机推荐
- 阿里云服务器安装Docker
在阿里云服务器上安装Docker,服务器的系统是CentOS 7.6, 所以可以看官方Docker安装文档:https://docs.docker.com/install/linux/docker-c ...
- gRPC (1):入门及服务端创建和调用原理
1. RPC 入门 1.1 RPC 框架原理 RPC 框架的目标就是让远程服务调用更加简单.透明,RPC 框架负责屏蔽底层的传输方式(TCP 或者 UDP).序列化方式(XML/Json/ 二进制)和 ...
- Python之操作文件和目录
Python内置的os模块可以直接调用操作系统提供的接口函数. # coding=utf-8 # 在指定目录以及指定目录的所有子目录下查找文件名包含指定字符串的文件,并打印出相对路径 import o ...
- In Triangle Test / To Left Test
2020-01-09 14:51:29 如何高效的判断一个点是否是包含在一个三角形的内部是计算几何里的一个基础问题. In Triangle Test问题也可以用来解决计算几何里的一个基础问题就是 凸 ...
- [树的深度] Party
Party A company has n employees numbered from 1 to n. Each employee either has no immediate manager ...
- C++实现秒表
完整代码下载 思路概括:如果有键按下,判断按下的是什么键并处理.没有键按下,计时.传统的Sleep无法满足秒表精确到百毫秒的需求,这里使用更精确的clock,clock的作用是统计从程序开始运行到现在 ...
- Hive学习笔记七
目录 函数 一.系统自带函数 二.自定义函数 三.自定义UDF函数开发案例 压缩和存储 一.Hadoop源码编译支持Snappy压缩 1.资源准备 2.jar包安装 3.编译源码 二.Hadoop压缩 ...
- [算法]移除指定元素&strSr()的实现
移除指定元素 题目 给你一个数组 nums 和一个值 val,你需要 原地 移除所有数值等于 val 的元素,并返回移除后数组的新长度. 不要使用额外的数组空间,你必须仅使用 O(1) 额外空间并 原 ...
- javascript实现炫酷魔方
实现效果: 魔方动态转换,同时每个面里的每个块都能进行动态变换. 实现代码: <!DOCTYPE html> <html> <head> <meta char ...
- Lisp-01: 相关开发环境配置部署
Common Lisp 学习笔记系列01 要学一门编程语言,首先需要将语言的环境配置好.如果想要个直接上手的环境,感谢日本的大神 Shirakumo,打造了一个 Common Lisp 的 IDE - ...