Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java program on name Initials

Tags:

java

string

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

like image 563
user3291928 Avatar asked Jun 27 '26 21:06

user3291928


2 Answers

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)

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

like image 40
lilalinux Avatar answered Jun 29 '26 11:06

lilalinux



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!