Java学习笔记1

时间:2021-08-01 14:44:10

学习一个Coursera的Data-structures-optimizing-performance。

Working with String in Java

Flesh score

Flesh score measures if a doc is easy to read, high -> easy to read.

Flesh score = 206.835 - 1.015(#words/#sentences) - 84.6(#syllables/#words)

String Basics

Strings are objects, not primitive types.
String text = new String("Hello World"); //'text' is a reference;

Strings are immutable
String s = "hello";
s.concat(" word"); // s doesn't change
System.out.println(s); // Only print hello
Interned Strings
String text2 = "hello world";
String text3 = "hello world"; // text2 == text3
String s1 = "Java";
String s2 = "Java";
String s3 = s2;
String s4 = new String "Java"; // new will always create new object, so only 2 string objects here
Compare Strings

Always use .equals to compare strings.

String text1 = new String("Hello world");
String text2 = "Hello world";
text1.equals(text2) //true;
text1 == text2; //false
Built-in string functions
  • length
  • toCharArray
String word = new String("hello world");
for (char c : word.toCharArray()) { //for-each loop
// some code here
}
  • charAt
String word = "test";
char letter = word.charAt(0);
//char letter = word[0]; error, Strings are objects \
that store arrays of characters using array notation
  • indexOf
String text = "Can you hear me? Hello, hello?";
int index = text.indexOf("he"); // index is 8
index = text.indexOf("He"); // index is 17
index = text.indexOf("help"); // index is -1
  • split
String text = "Can you hear me? Hello, hello?";
String[] words = text.split(" ");
String text2 = "Can you"; // two spaces;
String[] w2 = text2.split(" ");
//text2 = ["Can", "", "you"]

Regular Expression: split(String regex)

Basic Regular Expression
  • + one or more
"it+" == "i(t)+" -> ["it", "itt", ...]
  • * Asterisk zero or more

  • | Vertical bar or

  • [ ] brackets set

[abc] // anything in the set
[a-z] // - indicate a range
[^a-z123] // ^ **Caret** sign indicates NOT any characters in this set
  • Example:

get all word: "Any contiguous sequence of alphabetic characters".

[a-zA-A]+

get all sentences: "A sequence of any characters ending with end of sentence punctuation(.!?)"

[^!?.]+