用特定字符替换字符串空格的 Java 程序
在本文中,我们将了解如何用特定字符替换字符串空格。字符串是一种包含一个或多个字符且用双引号(“ ”)引起来的数据类型。
以下是相同内容的演示:
假设我们的输入为:
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
广告