Java
 Computer >> コンピューター >  >> プログラミング >> Java

文字列のスペースを特定の文字に置き換えるJavaプログラム


この記事では、文字列のスペースを特定の文字に置き換える方法を理解します。文字列は、1つ以上の文字を含み、二重引用符(“”)で囲まれたデータ型です。

以下は同じのデモンストレーションです-

入力がであると仮定します −

Input string: Java Program is fun to learn
Input character: $

必要な出力は

The string after replacing spaces with given character is:
Java$Program$is$fun$to$learn

アルゴリズム

Step 1 - START
Step 2 - Declare a string namely input_string, a char namely input_character.
Step 3 - Define the values.
Step 4 - Using the function replace(), replace the white space with the specified character.
Step 5 - Display the result
Step 6 - Stop

例1

ここでは、「main」関数の下ですべての操作をバインドします。

public class Demo {
   public static void main(String[] args) {
      String input_string = "Java Program is fun to learn";
      System.out.println("The string is defined as: " +input_string);
      char input_character = '$';
      System.out.println("The character is defined as: " +input_character);
      input_string = input_string.replace(' ', input_character);
      System.out.println("The string after replacing spaces with given character is: ");
      System.out.println(input_string);
   }
}

出力

The string is defined as: Java Program is fun to learn
The character is defined as: $
The string after replacing spaces with given character is:
Java$Program$is$fun$to$learn

例2

ここでは、操作をオブジェクト指向プログラミングを示す関数にカプセル化します。

public class Demo {
   static void space_replace(String input_string, char input_character){
      input_string = input_string.replace(' ', input_character);
      System.out.println("The string after replacing spaces with given character is: ");
      System.out.println(input_string);
   }
   public static void main(String[] args) {
      String input_string = "Java Program is fun to learn";
      System.out.println("The string is defined as: " +input_string);
      char input_character = '$';
      System.out.println("The character is defined as: " +input_character);
      space_replace(input_string, input_character);
   }
}

出力

The string is defined as: Java Program is fun to learn
The character is defined as: $
The string after replacing spaces with given character is:
Java$Program$is$fun$to$learn

  1. 文字列がJavaの特定のサブ文字列で始まっているかどうかを確認するにはどうすればよいですか?

    文字列 クラスは文字列を表すために使用できます。Javaプログラムのすべての文字列リテラルは、Stringクラスのインスタンスとして実装されます。文字列は定数であり、その値は変更できません (不変 )一度作成されます。 startsWith()を使用できます 文字列のメソッド 文字列が特定の文字列で始まるかどうかをチェックするクラス。trueまたはfalseのブール値を返します。 構文 public boolean startsWith(String prefix) 例 public class StringStartsWithSubStringTest {    

  2. Javaで文字列の最大出現文字を出力するにはどうすればよいですか?

    文字列 クラスは、文字列を表すために使用できます 、Javaプログラムのすべての文字列リテラルは、文字列のインスタンスとして実装されます。 クラス。文字列は定数であり、その値は変更できません(不変) 作成したら。 以下のプログラムでは、最大発生文字を印刷できます。 与えられた文字列の。 例 public class MaxOccuredCharacterTest {    public static void main(String[] args) {       String str1 = maxOccuredChar("tutor