Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

문자열에서 모든 공백을 제거하는 Java 프로그램

<시간/>

이 기사에서는 문자열에서 모든 공백을 제거하는 방법을 이해할 것입니다. String은 하나 이상의 문자를 포함하고 큰따옴표(" ")로 묶인 데이터 유형입니다.

아래는 동일한 데모입니다 -

입력이 다음과 같다고 가정 -

Input string: Java programming is fun to learn.

원하는 출력은 -

The string after replacing white spaces: Javaprogrammingisfuntolearn.

알고리즘

Step 1 - START
Step 2 - Declare two strings namely String input_string and result.
Step 3 - Define the values.
Step 4 - Use the function replaceAll("\\s", "") to replaces all the white spaces with blank spaces.
Step 5 - Display the result
Step 6 - Stop

예시 1

여기에서 모든 작업을 'main' 기능 아래에 묶습니다.

public class Demo {
   public static void main(String[] args) {
      String input_string = "Java programming is fun to learn.";
      System.out.println("The string is defined as: " + input_string);
      String result = input_string.replaceAll("\\s", "");
      System.out.println("\nThe string after replacing white spaces: " + result);
   }
}

출력

The string is defined as: Java programming is fun to learn.

The string after replacing white spaces: Javaprogrammingisfuntolearn.

예시 2

여기에서 객체 지향 프로그래밍을 나타내는 함수로 작업을 캡슐화합니다.

public class Demo {
   public static String string_replace(String input_string){
      String result = input_string.replaceAll("\\s", "");
      return result;
   }
   public static void main(String[] args) {
      String input_string = "Java programming is fun to learn.";
      System.out.println("The string is defined as: " + input_string);
      String result = string_replace(input_string);
      System.out.println("\nThe string after replacing white spaces: " + result);
   }
}

출력

The string is defined as: Java programming is fun to learn.

The string after replacing white spaces: Javaprogrammingisfuntolearn.