空白文字解析用のユーティリティメソッドの作成
では、文字列内の空白文字を解析する専用のメソッドを作成して、コードをより再利用可能にするためにリファクタリングしましょう。これは、コードを論理的で再利用可能な単位に整理するためのソフトウェア開発における一般的な手法です。
CharacterSpace.java
ファイルを以下のコードで更新します。
public class CharacterSpace {
/**
* Analyzes a string and prints information about space characters
* @param text The string to analyze
* @return The number of space characters found
*/
public static int analyzeSpaceCharacters(String text) {
if (text == null) {
System.out.println("Error: Input string is null");
return 0;
}
int spaceCount = 0;
System.out.println("The string is: " + text);
System.out.println("\nChecking for space characters:");
for (int i = 0; i < text.length(); i++) {
char currentChar = text.charAt(i);
if (Character.isSpaceChar(currentChar)) {
spaceCount++;
System.out.println("Space character found at position " + i +
" (character: '" + currentChar + "')");
}
}
System.out.println("\nTotal space characters found: " + spaceCount);
return spaceCount;
}
public static void main(String[] args) {
// Test with different strings
String text1 = "Hello World!";
String text2 = "NoSpacesHere";
String text3 = " Multiple Spaces ";
System.out.println("=== Example 1 ===");
analyzeSpaceCharacters(text1);
System.out.println("\n=== Example 2 ===");
analyzeSpaceCharacters(text2);
System.out.println("\n=== Example 3 ===");
analyzeSpaceCharacters(text3);
}
}
この更新されたコードでは、以下のことを行っています。
- 文字列の入力を受け取り、見つかった空白文字の数を返す
analyzeSpaceCharacters
という新しいメソッドを作成しました。
- このメソッドは、入力が null の場合を処理し、見つかった各空白文字に関する詳細な出力を提供します。
main
メソッドでは、この関数を3つの異なる文字列でテストし、様々な入力に対する動作を確認します。
この更新されたプログラムをコンパイルして実行しましょう。
javac CharacterSpace.java
java CharacterSpace
各テストケースについて、空白文字が見つかった位置と各文字列の空白文字の総数を示す詳細な出力が表示されるはずです。出力は以下のようになります。
=== Example 1 ===
The string is: Hello World!
Checking for space characters:
Space character found at position 5 (character: ' ')
Total space characters found: 1
=== Example 2 ===
The string is: NoSpacesHere
Checking for space characters:
Total space characters found: 0
=== Example 3 ===
The string is: Multiple Spaces
Checking for space characters:
Space character found at position 0 (character: ' ')
Space character found at position 1 (character: ' ')
Space character found at position 10 (character: ' ')
Space character found at position 11 (character: ' ')
Space character found at position 12 (character: ' ')
Space character found at position 20 (character: ' ')
Space character found at position 21 (character: ' ')
Space character found at position 22 (character: ' ')
Total space characters found: 8
この例は、空白文字解析用の再利用可能なメソッドを作成し、異なる入力でテストする方法を示しています。