![](/img/trans.png)
[英]How to find the index of the first and second Uppercase Letter in a string?
[英]How to randomly return an Uppercase letter in a String?
我有一个字符串作为输入,我想将整个字符串转换为小写,除了一个需要大写的随机字母。
我尝试了以下内容:splited是输入字符串数组
word1 = splited[0].length();
word2 = splited[1].length();
word3 = splited[2].length();
int first = (int) Math.random() * word1;
String firstLetter = splited[0].substring((int) first, (int) first + 1);
String lowcase1 = splited[0].toLowerCase();
char[] c1 = lowcase1.toCharArray();
c1[first] = Character.toUpperCase(c1[first]);
String value = String.valueOf(c1);
System.out.println(value);
当我尝试打印字符串时,它总是将第一个字母作为大写字母返回,其余字符串是小写字母。 为什么它不是返回随机字母而是第一个字母。
干杯
理解你的问题的关键是你将word1乘以零。
你的代码int first = (int) Math.random() * word1;
每次返回相同的数字因为(int) Math.random()
每次都返回零。
这是Math.random()的javadoc
返回带有正号的double值,大于或等于0.0且小于1.0。
一旦转换为整数,任何小于1且大于0的数字为零。 这是因为浮点数被截断。
String str = "my string";
Random rand = new Random(str.length());
int upperIndex = rand.nextInt();
StringBuffer strBuff = new StringBuffer(str.toLowerCase());
char upperChar = Character.toUpperCase(strBuff.charAt(upperIndex));
strBuff.replace(upperIndex, upperIndex, upperChar);
System.out.println(strBuff.toString());
因为
Math.random()
返回0到1之间的值,所以
(int) Math.random()
始终为零,因为零乘以任何值都为零
(int) Math.random() * word1;
也总是零。 你需要括号。
int first = (int) (Math.random() * word1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.