名字缩写的 Java 程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21989714/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 11:53:04  来源:igfitidea点击:

Java program on name Initials

javastring

提问by user3291928

I am writing a program that will give the Initials of the name(String) user gives as input. I want to use the Space functionwhile writing the name as the basis of the algorithm. For eg:

我正在编写一个程序,它将提供用户提供的姓名首字母(字符串)作为输入。我想使用Space functionwhile 编写名称作为算法的基础。例如:

<Firstname><space><Lastname>

taking the char once in a for loop and checking if there is a space in between, if there is it will print the charecter that was just before. Can someone tell me how to implement this? I'm trying this but getting one error.

在 for 循环中取一次字符并检查它们之间是否有空格,如果有,它将打印之前的字符。有人能告诉我如何实现这个吗?我正在尝试此操作,但出现一个错误。

Any help is dearly appreaciated.. P.S- i am new to java and finding it a lot intresting. Sorry if there is a big blunder in the coding

任何帮助都非常感谢.. PS-我是 Java 新手,发现它很有趣。对不起,如果编码中有一个大错误

public class Initials {
    public static void main(String[] args) {
        String name = new String();
        System.out.println("Enter your name: ");
        Scanner input = new Scanner(System.in);
        name = input.nextLine();

        System.out.println("You entered : " + name);
        String temp = new String(name.toUpperCase());

        System.out.println(temp);

        char c = name.charAt(0);
        System.out.println(c);

        for (int i = 1; i < name.length(); i++) {
            char c = name.charAt(i);

            if (c == '') {
                System.out.println(name.charAt(i - 1));
            }

        }
    }
}

EDIT: Ok Finally got it. The algorithm is a lot fuzzy but its working and will try to do it next time with Substring..

编辑:好的终于明白了。该算法很模糊,但它可以工作,下次将尝试使用 Substring..

for (int i = 1; i < temp.length(); i++) {
    char c1 = temp.charAt(i);

    if (c1 == ' ') {
        System.out.print(temp.charAt(i + 1));
        System.out.print(".");
    }
}

Thanks a lot guys :)

非常感谢各位:)

采纳答案by 3j8km

I will do something like this: Remember, you only need the inicial characters

我会做这样的事情:记住,你只需要初始字符

public staticvoid main (String[] args){
   String name;
   System.out.println("Enter your complete name");
   Scanner input = new Scanner(System.in);
   name = input.nextLine();
   System.out.println("Your name is: "+name);
   name=" "+name;
   //spacebar before string starts to check the initials
   String ini; 
   // we use ini to return the output
   for (int i=0; i<name.length(); i++){
      // sorry about the 3x&&, dont remember the use of trim, but you
      // can check " your name complete" if " y"==true y is what you want
      if (name.charAt(i)==" " && i+1 < name.length() && name.charAt(i+1)!=" "){
         //if i+1==name.length() you will have an indexboundofexception
         //add the initials
         ini+=name.charAt(i+1);
      }
   }
   //after getting "ync" => return "YNC"
   return ini.toUpperCase();
}

回答by markgiaconia

This works for me

这对我有用

public static void main(String[] args) {
    Pattern p = Pattern.compile("((^| )[A-Za-z])");
    Matcher m = p.matcher("Some Persons Name");
    String initials = "";
    while (m.find()) {
        initials += m.group().trim();
    }
    System.out.println(initials.toUpperCase());
}

Output:

输出:

run:
SPN
BUILD SUCCESSFUL (total time: 0 seconds)

回答by marmor

If you care about performance (will run this method many times), the extra charAt(i+1) isn't needed and is relatively costly. Also, it'll break on texts with double spaces, and will crash on names that end with a space.

如果您关心性能(将多次运行此方法),则不需要额外的 charAt(i+1) 并且成本相对较高。此外,它会打破双空格文本,并会崩溃的名称为此有空间

This is a safer and faster version:

这是一个更安全、更快的版本:

public String getInitials(String name) {
        StringBuilder initials = new StringBuilder();
        boolean addNext = true;
        if (name != null) {
            for (int i = 0; i < name.length(); i++) {
                char c = name.charAt(i);
                if (c == ' ' || c == '-' || c == '.') {
                    addNext = true;
                } else if (addNext) {
                    initials.append(c);
                    addNext = false;
                }
            }
        }
        return initials.toString();
    }

回答by lilalinux

Simply use a regex:

只需使用正则表达式:

  1. keep only characters that are following a whitespace
  2. remove all remaining whitespace and finally
  3. make it upper case:
  1. 只保留空格后面的字符
  2. 删除所有剩余的空格,最后
  3. 使其大写:

" Foo Bar moo ".replaceAll("([^\\s])[^\\s]+", "$1").replaceAll("\\s", "").toUpperCase();

" Foo Bar moo ".replaceAll("([^\\s])[^\\s]+", "$1").replaceAll("\\s", "").toUpperCase();

=> FBM

=> FBM

回答by Minu

public String getInitials() {
          String initials="";
          String[] parts = getFullName().split(" ");
          char initial;
          for (int i=0; i<parts.length; i++){
              initial=parts[i].charAt(0);
              initials+=initial;                  
           }      
          return(initials.toUpperCase());
 }