user3291928
user3291928

Reputation: 85

Java program on name Initials

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

<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.

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

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..

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 :)

Upvotes: 3

Views: 36634

Answers (5)

Minu
Minu

Reputation: 33

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());
 }

Upvotes: 0

lilalinux
lilalinux

Reputation: 3031

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:

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

=> FBM

Upvotes: 4

Mark Giaconia
Mark Giaconia

Reputation: 3953

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)

Upvotes: 7

marmor
marmor

Reputation: 28179

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.

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();
    }

Upvotes: 0

3j8km
3j8km

Reputation: 12

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();
}

Upvotes: 0

Related Questions