我可以使用indexOf从字符串中提取字符

时间:2013-11-23 19:57:11

标签: java

我试图使用index来基本上在每个空格后打印字符串中的第一个字母

我希望它能抓住一个人姓的第一个字母输入,以便退出这些内容,所以如果他们输入比利鲍勃乔,它会抓住BBJ并将其打印出来,就像我试图让它从每个空白中去+1抓住字符。

我不能使用chartAt,因为我不知道用户会给出的输入。

我有这个代码我可以让它去一个特定的空白区但是不能让它只抓住空白之后的第一个字母,它会占据整个strign之后

        String str ="Billy Joe Bob";

    int targetMatch = 1;
    int offset = 0;
    for(int i = 0 ; i < targetMatch; i++){
         int position = str.indexOf(' ',offset);
         if(position != -1){
              offset = position+1;            
            }
         }

    String result = str.substring(offset);
    System.out.println(result);

任何帮助都将不胜感激。

3 个答案:

答案 0 :(得分:3)

String str ="Billy Joe Bob";

    int targetMatch = 1;
    int offset = 0;
    int position = str.indexOf(' ',offset);
    String result = "";
    result += str.substring(0, 1);
    while(position != -1){
        position++;
        result += str.substring(position,position+1);
        position = str.indexOf(' ', position);
    }
    System.out.println(result);

试试这个

答案 1 :(得分:0)

理想情况下,您只需使用String.split将字符串拆分为空格。 E.g。

String str = "foo bar qux";
for(String tok: str.split("\s+"))
     System.out.println(tok.charAt(0));

答案 2 :(得分:0)

我能想到的最简单的解决方案是使用String.split

String str ="Billy Joe Bob";
for (String word : str.split("\s+")) {
    if (word.length >= 1) {
        System.out.print(word.charAt(0));
    }
}