O processamento de strings é muito importante em muitas linguagens de programação. Isso também é frequentemente solicitado em entrevistas. Se você não tiver um domínio firme, é fácil deixar de responder.
String Java
Em Java, String
é um tipo de referência. No entanto, como as strings são amplamente utilizadas na programação Java, o compilador Java processa as strings e pode usar diretamente dois "
para representar as strings.
// 我们通常的做法
String s = "Hello World!";
// 下面这种写法也可以
String s = new String("Hello World!");
// 还可以这样写 String内部是通过一个char[]表示的
String s = new String(new char[] {
'H', 'e', 'l', 'l', 'o', '!'});
Um recurso importante das strings Java é que as strings são imutáveis (conteúdo).
- A variável de string declarada é mutável
- A string em si é imutável
String s1 = "Hello"; // 此时有一块内存存着"Hello", 且可通过s1访问它
s1 = "World"; // 此时有一块内存存着"Hello", 还有一块内存存着"World", 通过s1只能找到"World", "Hello"并未改变
Aqui você pode dar uma olhada em uma análise simples da memória da pilha
Manipulação de string Java
Comparação de cordas
Você só pode usar equals()
métodos ==
que não são confiáveis.
por exemplo
String s1 = "Hello";
String s2 = "Hello";
String s3 = "World";
String s4 = "wOrLd";
System.out.println(s1.equals(s2)); // true
System.out.println(s3.equals(s4)); // false
System.out.println(s3.equalsIgnoreCase(s4)); // true
Pesquisa de substring ou pesquisa
indexOf()
Encontre a substring da esquerda para a direita e retorne o subscritolastIndexOf()
Encontre a substring da direita para a esquerda e retorne o subscritocontains()
Determine se deseja incluir uma determinada substringstartWith()
Determine se deve começar com uma determinada substringendWith()
Determine se termina com uma determinada substring
String s1 = "Are you ok ?";
System.out.println(s1.indexOf("o"));
System.out.println(s1.lastIndexOf('o'));
System.out.println(s1.contains("you"));
System.out.println(s1.startsWith("are"));
System.out.println(s1.endsWith(" ?"));
// 输出:
// 5
// 8
// true
// false
// true
Emenda de cordas
+
Splicing
Ao produzir, você pode usar diretamente +
a saída de emenda de strings e números.
String s1 = "Hello";
int n1 = 8848;
float f1 = 10.24f;
boolean b1 = false;
System.out.println(s1 + n1 + f1+ b1);
// 输出:
// Hello884810.24false
Use +
splicing entre strings
String s1 = "Hello";
String s2 = "World";
String s3 = s1 + ' ' + s2; // s3 = "Hello World"
- Método estático
join()
: use uma string para concatenar uma matriz de strings
String[] sArr = {
"Hello", "Hi", "Bye"};
String s = String.join("--", sArr); // 静态方法 所以是String.join()
System.out.println(s);
// 输出:
// Hello--Hi--Bye
Remova as strings em branco à esquerda e à direita
trim()
trim()
Retire a cabeça ea cauda (Inglês),空格
,,\t
\r
\n
String s1 = " Hello \u3000"; // \u3000是中文空格Unicode编码(站长之家有转换工具 感兴趣的可以看看)
String s2 = "\t\nWorld \r ";
System.out.println(s1.trim());
System.out.println(s2.trim());
// 输出:
// `Hello `
// `World`
strip()
strip()
trim()
Funções incluídas , e também pode remover espaços semelhantes aos espaços chinesesstripLeading
Remova apenas o espaço esquerdostripTrailing
Remova apenas o espaço à direita
String s1 = " Hello \u3000";
String s2 = "\t\nWorld \r ";
System.out.println(s1.strip());
System.out.println(s2.strip());
// 输出:
// `Hello`
// `World`
Segmentação de string
split
String s1 = "Are you ok ?";
String[] sArr = s1.split(" ");
System.out.println(Arrays.toString(sArr)); // 推荐这种打印方式 别用for
// 输出:
// [Are, you, ok, ?]
substring()
substring()
Sua essência é extrair substrings, o que também pode ser considerado uma espécie de segmentação.
String s1 = "Are you ok ?";
System.out.println(s1.substring(4)); // [4, s1.length()-1]
System.out.println(s1.substring(4, 7)); // [4, 7)
// 输出:
// you ok ?
// you
Substituição de substring
replace()
replace()
Não altere a string original, retornará uma nova string
String s1 = "Are you ok ?";
String s2 = s1.replace("o", "ooo"); // 要么用另一个变量接收 要么直接打印 s1未改变
System.out.println(s2);
Saída formatada
format()
Método estático, preste atençãoString.format()
a
String s = "My name is %s, and I'm %d years olds.";
System.out.println(String.format(s, "XXX", 18));
// 输出:
// My name is XXX, and I'm 18 years olds.
Conversão de tipo
Converter entre String e char []
String s1 = "Hello World!";
char[] sArr = s1.toCharArray();
String s2 = new String(sArr);
System.out.println(Arrays.toString(sArr));
System.out.println(s2);
// 输出:
// [H, e, l, l, o, , W, o, r, l, d, !]
// Hello World!
Conversão de string e tipo de dados básicos
Aqui a conversão é relativamente simples, é preciso prestar atenção para 静态方法
não pertencer a instância, deve 类
ser chamada
String s1 = "123";
String s2 = "123.45f";
String s3 = "false";
float f = 80.86f;
System.out.println(Integer.parseInt(s1));
System.out.println(Float.parseFloat(s2));
System.out.println(Boolean.parseBoolean(s3));
System.out.println(String.valueOf(f));
// 输出:
// 123
// 123.45
// false
// 80.86