如何使用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);
}
}
答案 0 :(得分:1)
我会用这样的东西:
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")
将字符串溢出到每个空白字符并存储新的&#34;子字符串&#34;在数组中。现在迭代数组并获取每个字符串的第一个字符并将其附加到String。
如果您希望确定首字母大写,则可以使用System.out.println(sb.toString().toUpperCase())
。
答案 1 :(得分:0)
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);
}
}