0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Java】文字列操作・整形まとめ10選

Posted at

はじめに

2年目になって配属された業務でJavaを本格的に触り始めたものです。
業務内で文字列操作をするタイミングが少し多かったのでどんなものがあるのか調べました。
本記事では調べた中でよく使いそうと思ったもの、個人的に知らなかったものを備忘録としてまとめています

空白・タブ・改行の除去

String s = "  \t Hello \n ";
String cleaned = s.trim();  // 前後の空白除去
String noSpaces = s.replaceAll("\\s+", "");  // 全ての空白・改行除去

数字かどうかチェック

String input = "1234";
boolean isNumeric = input.matches("\\d+");  // true

桁区切りの数値文字列に変換(3桁カンマ)

int number = 1234567;
String formatted = String.format("%,d", number);  // "1,234,567"

パディング(0埋めなど)

int id = 42;
String padded = String.format("%05d", id);  // "00042"

大文字・小文字変換

String s = "Java";
s.toLowerCase();  // "java"
s.toUpperCase();  // "JAVA"

文字列の一部をマスク

String phone = "09012345678";
String masked = phone.replaceAll("\\d{4}$", "****");  // "0901234****"

文字列の結合

String[] names = {"Tanaka", "Sato", "Suzuki"};
String joined = String.join(", ", names);  // "Tanaka, Sato, Suzuki"

区切り文字で分割

String csv = "apple,banana,grape";
String[] items = csv.split(",");  // ["apple", "banana", "grape"]

正規表現を使った置換

String text = "abc123xyz";
String replaced = text.replaceAll("\\d+", "***");  // "abc***xyz"

HTMLエスケープ / アンエスケープ(Apache Commons)

import org.apache.commons.text.StringEscapeUtils;

String html = "<div>Hello</div>";
String escaped = StringEscapeUtils.escapeHtml4(html);  // "&lt;div&gt;Hello&lt;/div&gt;"

おまけ:StringBuilderで高速連結

StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" ");
sb.append("World!");
String result = sb.toString();  // "Hello World!"

※Stringだと連結するたびに新しいオブジェクトが生成される関係でコストがかかるらしい。

参考リンク

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?