ランダムな文字列を作成するJavaプログラム
この記事では、ランダムな文字列を作成する方法を理解します。文字列は、1つ以上の文字を含み、二重引用符(“”)で囲まれたデータ型です。
以下は同じのデモンストレーションです-
入力がであると仮定します −
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
-
文字列内の母音をカウントするJavaプログラム
以下が私たちの文字列だとしましょう- String myStr = "Jamie"; 同じ変数の母音を計算するので、変数count=0に設定します。すべての文字をループして母音を数えます- for(char ch : myStr.toCharArray()) { ch = Character.toLowerCase(ch); if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u
-
Javaで文字列を比較する方法
文字列が等しいかどうかを比較するには、Stringオブジェクトのequalsを使用する必要があります またはequalsIgnoreCase メソッド。 ==を使用すべきでない理由もわかります 文字列を比較する演算子。 文字列とequals()メソッドの比較 Javaで2つの文字列を比較する必要があり、文字列の大文字と小文字も気にする必要がある場合は、equals()を使用できます。 メソッド。 たとえば、次のスニペットは、文字列の2つのインスタンスが大文字小文字を含むすべての文字で等しいかどうかを判断します。 public class CompareTwoStrings { p