이 기사에서는 문자열을 'N'개의 동일한 부분으로 나누는 방법을 이해할 것입니다. String은 하나 이상의 문자를 포함하고 큰따옴표(" ")로 묶인 데이터 유형입니다.
아래는 동일한 데모입니다 -
입력이 다음과 같다고 가정 -
Input string: Java Program is fun!
원하는 출력은 -
The length of the string is: 20 4 equal parts of given string are Java Progr am is fun!
알고리즘
Step 1 - START Step 2 - Declare a string namely input_string, two integers namely string_length and N. Step 3 - Define the values. Step 4 - Initiatize a temporary variable to 0. Step 5 - Compute the parts in the string by dividing the length of the string by ‘N’. Step 6 - If the string is not divisible by N, display a relevant message. Given that the string length is divisible by N, iterate through the string. Step 7 - Fetch the substring within the range of string length and N in every iteration. Assign this value to a variable. Step 8 - Increment the temporary variable after every iteration. Step 9 - Display the N parts of the string on the console by iterating over the split parts of the string. Step 10 - Stop
예시 1
여기에서 모든 작업을 'main' 기능 아래에 묶습니다.
public class Demo { public static void main(String[] args) { String input_string = "Java Program is fun!"; System.out.println("The string is defined as: " +input_string); int string_length = input_string.length(); System.out.println("The length of the string is: " +string_length); int N = 4; int temp = 0, string_parts = string_length/N; String[] equalStr = new String [N]; if(string_length % N != 0) { System.out.println("The string cannot be divided int "+ N +" parts."); } else { for(int i = 0; i < string_length; i = i+string_parts) { String part = input_string.substring(i, i+string_parts); equalStr[temp] = part; temp++; } System.out.println(N + " equal parts of given string are "); for(int i = 0; i < equalStr.length; i++) { System.out.println(equalStr[i]); } } } }
출력
The string is defined as: Java Program is fun! The length of the string is: 20 4 equal parts of given string are Java Progr am is fun!
예시 2
여기에서 객체 지향 프로그래밍을 나타내는 함수로 작업을 캡슐화합니다.
public class Demo { static void divide_string(String input_string, int N){ int string_length = input_string.length(); System.out.println("The length of the string is: " +string_length); int temp = 0, string_parts = string_length/N; String[] equalStr = new String [N]; if(string_length % N != 0) { System.out.println("The string cannot be divided int "+ N +" parts."); } else { for(int i = 0; i < string_length; i = i+string_parts) { String part = input_string.substring(i, i+string_parts); equalStr[temp] = part; temp++; } System.out.println(N + " equal parts of given string are "); for(int i = 0; i < equalStr.length; i++) { System.out.println(equalStr[i]); } } } public static void main(String[] args) { String input_string = "Java Program is fun!"; System.out.println("The string is defined as: " +input_string); int N = 4; divide_string(input_string, N); } }
출력
The string is defined as: Java Program is fun! The length of the string is: 20 4 equal parts of given string are Java Progr am is fun!