이 기사에서는 임의의 문자열을 생성하는 방법을 이해할 것입니다. String은 하나 이상의 문자를 포함하고 큰따옴표(" ")로 묶인 데이터 유형입니다.
아래는 동일한 데모입니다 -
입력이 다음과 같다고 가정 -
The size of the string is defined as: 10
원하는 출력은 -
Random string: ink1n1dodv
알고리즘
Step 1 - START Step 2 - Declare an integer namely string_size, a string namely alpha_numeric and an object of StringBuilder namely string_builder. Step 3 - Define the values. Step 4 - Iterate for 10 times usinf a for-loop, generate a random value using the function Math.random() and append the value using append() function. Step 5 - Display the result Step 6 - Stop
예시 1
여기에서 모든 작업을 'main' 기능 아래에 묶습니다.
public class RandomString {
public static void main(String[] args) {
int string_size = 10;
System.out.println("The size of the string is defined as: " +string_size);
String alpha_numeric = "0123456789" + "abcdefghijklmnopqrstuvxyz";
StringBuilder string_builder = new StringBuilder(string_size);
for (int i = 0; i < string_size; i++) {
int index = (int)(alpha_numeric.length() * Math.random());
string_builder.append(alpha_numeric.charAt(index));
}
String result = string_builder.toString();
System.out.println("The random string generated is: " +result);
}
} 출력
The size of the string is defined as: 10 The random string generated is: ink1n1dodv
예시 2
여기에서 객체 지향 프로그래밍을 나타내는 함수로 작업을 캡슐화합니다.
public class RandomString {
static String getAlphaNumericString(int string_size) {
String alpha_numeric = "0123456789" + "abcdefghijklmnopqrstuvxyz";
StringBuilder string_builder = new StringBuilder(string_size);
for (int i = 0; i < string_size; i++) {
int index = (int)(alpha_numeric.length() * Math.random());
string_builder.append(alpha_numeric.charAt(index));
}
return string_builder.toString();
}
public static void main(String[] args) {
int string_size = 10;
System.out.println("The size of the string is defined as: " +string_size);
System.out.println("The random string generated is: ");
System.out.println(RandomString.getAlphaNumericString(string_size));
}
} 출력
The size of the string is defined as: 10 The random string generated is: ink1n1dodv