如何使用indexOf((和CharAt((方法来显示这样的输出?"B R A M">
public class Test {
public static void main(String[] args) {
String s = new String("Business Requirement And Management");
String shortForm = "";
int index = 0;
int i=0;
while(i<s.length()) {
if(s.charAt(i) == ' '){
index = s.indexOf(" ");
shortForm += s.charAt(index+1);
}
i++;
}
System.out.println(shortForm);
}
}
我会使用这样的东西:
StringBuilder sb = new StringBuilder();
String s = "Business Requirement And Management";
String[] splitted = s.split("\s");
for(String str : splitted)
{
sb.append(str.charAt(0)).append(" ");
}
System.out.println(sb.toString());
解释:
我们通过调用 split("s")
将 String 洒在每个空格字符上,并将新的"子字符串"存储在数组中。现在遍历数组并获取每个字符串的第一个字符并将其附加到字符串中。(可选(如果要确定首字母为大写,可以使用System.out.println(sb.toString().toUpperCase())
。
public class Test {
public static void main(String[] args) {
String s = new String("Business Requirement And Management");
String shortForm = "";
int index = 0;
while(s.length() > 0) {
index = s.indexOf(" ");
if(index == -1 || index == s.length() -1) break;
shortForm += s.charAt(index+1);
s = s.substring(index+1);
}
System.out.println(shortForm);
}
}