Web系開発メモ

Java, C#, HTML, CSS, JavaScript のことなどを書いてます。

Java 左トリムをする方法(先頭のスペースを削除する方法)

Java の文字列で、左トリムをする方法(先頭の半角スペースを削除する方法)を書いていきます。

バージョン

動作確認で使用した製品のバージョンは以下の通りです。

コード例

プログラムの例は以下の通りです。

package org.example;

public abstract class Trim {
  public static String leftSpace(String str) {
    char[] chars = str.toCharArray();
    int i = 0;
    for (; i < chars.length; i++) {
      if (chars[i] != ' ') break;
    }
    if (i == 0) return str;
    else return str.substring(i);
  }
}

null チェックはしないで、半角スペースのみトリムします。

テストケース

JUnit5 のテストケースは以下の通りです。

package org.example;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;

class TrimTest {
  @ParameterizedTest
  @CsvSource({
    "' 吉田 太郎', '吉田 太郎'",  // 先頭スペース1つ
    "'  吉田 太郎', '吉田 太郎'",  // 先頭スペース2つ
    "'吉田 太郎', '吉田 太郎'",  // 先頭スペースなし
    "' 𠮷田 太郎', '𠮷田 太郎'",  // サロゲートペア「𠮷」
    "' ',''", // スペースのみ
    "'',''", // 空文字
  })
  void testLeftTrim(String target, String expected) {
    // 実行
    String result = Trim.leftSpace(target);

    // 検証
    assertEquals(expected, result);
  }
  @Test
  void testLeftTrimNull() {
    assertThrows(NullPointerException.class, () -> {
      Trim.leftSpace(null);
    });
  }
}

サロゲートペアの文字があっても動くことを確認しています。

ビルドファイル

Maven のビルドファイルは以下の通りです。

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>org.example</groupId>
  <artifactId>trim</artifactId>
  <version>1.0.0</version>
  <packaging>jar</packaging>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <maven.compiler.source>17</maven.compiler.source>
    <maven.compiler.target>17</maven.compiler.target>
  </properties>

  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.junit</groupId>
        <artifactId>junit-bom</artifactId>
        <version>5.9.2</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <dependencies>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>3.0.0-M8</version>
      </plugin>
    </plugins>
  </build>
</project>