JavaRush /จาวาบล็อก /Random-TH /การสร้างสตริงที่มีความยาวคงที่
ttt
ระดับ
Симферополь

การสร้างสตริงที่มีความยาวคงที่

เผยแพร่ในกลุ่ม
สวัสดีตอนบ่ายทุกคน! ฉันจำเป็นต้องเขียนฟังก์ชันที่สร้างสตริงที่มีความยาวคงที่ จริงๆ แล้ว เมื่อดูเผินๆ มันก็ง่าย นั่นแหละที่เป็นอยู่ แต่มีความปรารถนาที่จะทำให้ฟังก์ชันนี้เร็วที่สุดเท่าที่จะเป็นไปได้ แล้วคำถามก็เกิดขึ้น - อย่างไร? จริงๆแล้วฉันสร้างรหัสนี้ วิธีที่เร็วที่สุดคือ GenerateString แต่ฉันเชื่อว่ามันสามารถเร่งความเร็วได้มากกว่านั้นอีก public class StringGenerator{ private int strLength; private StringGenerator() { } public static StringGenerator getStringFixedLengthGenerator(int length){ StringGenerator stringGenerator = new StringGenerator(); stringGenerator.setStrLength(length); return stringGenerator; } public void setStrLength(int strLength) { this.strLength = strLength; } public String generateNextFixedString(){ return new String(); } public String generateThreadString() { ExecutorService executor = Executors.newSingleThreadExecutor(); Callable task = () -> { return generateString(strLength/2); }; Future future = executor.submit(task); Future future1 = executor.submit(task); String str = ""; try{ str = future1.get().concat(future.get()); }catch (Exception e){ } executor.shutdown(); return str; } public String generateString(){ return generateString(strLength); } public String generateString(int stringLength) { String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; Random rng = new Random(); char[] text = new char[stringLength]; for (int i = 0; i < stringLength; i++) { text[i] = characters.charAt(rng.nextInt(characters.length())); } return new String(text); } public String createRandomString() { String mCHAR = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; int STR_LENGTH = strLength; // длина генерируемой строки Random random = new Random(); StringBuilder builder = new StringBuilder(); for (int i = 0; i < STR_LENGTH; i++) { int number = random.nextInt(mCHAR.length()); char ch = mCHAR.charAt(number); builder.append(ch); } return builder.toString(); } }
ความคิดเห็น
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION