考虑以下代码: 包q2b;
public class Q2b {
public static void main(String[] args) {
String kalimat = new String("Sue sells sea shells on the seashore!");
String upperLetter = "";
String removeLetter = "";
//Code to count the spacing in the string
for (int i = 0; i < kalimat.length(); i++) {
if (kalimat.charAt(i) == 's') {
upperLetter += 'S';
} else {
upperLetter += kalimat.charAt(i);
}
}
System.out.println("The letter modification in the string are :" + upperLetter);
}
}
我的问题: 我应该输入什么代码来获取多少个小写字母''被替换?
答案 0 :(得分:3)
添加:
int count = 0; // <-- here
for (int i = 0; i < kalimat.length(); i++) {
if (kalimat.charAt(i) == 's') {
upperLetter += 'S';
count++; // <-- and here
} else {
upperLetter += kalimat.charAt(i);
}
}
最后,您将在变量count
中获得替换次数。
答案 1 :(得分:2)
在处理循环外声明并初始化int
变量为0。当您使用s
替换S
时,处理时会增加它。
作为旁注,显然超出了这个问题的范围,但使用+
运算符进行重复的字符串连接是非常低效的。您应该使用StringBuilder
代替。
答案 2 :(得分:1)
根据我对您的问题的理解,以下代码可能对您有帮助,
声明变量&#39; count&#39;并且在每个小写字母的存在下它会增加&#39;在迭代中。
public class Q2b {
public static void main(String[] args) {
String kalimat = new String("Sue sells sea shells on the seashore!");
String upperLetter = "";
String removeLetter = "";
int count=0;
//Code to count the spacing in the string
for (int i = 0; i < kalimat.length(); i++) {
if (kalimat.charAt(i) == 's') {
upperLetter += 'S';
count++;
} else {
upperLetter += kalimat.charAt(i);
}
}
System.out.println("The letter modification in the string are :" + upperLetter);
System.out.println("Number of lower case letter 's' is :" + count);
}
}