Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the first character of each word in a String

Tags:

java

string

I am trying to get a program working which does the following:

Let's say we have a String called name, set to "Stack Overflow Exchange". I want to output to the user "SOE", with the first characters of each word. I tried with the split() method, but I failed to do it.

My code:

public class q4 {
    public static void main(String args[]) {
        String x = "michele jones";
        String[] myName = x.split("");
        for(int i = 0; i < myName.length; i++) {
            if(myName[i] == "") {
                String s = myName[i];
                System.out.println(s);
            }              
        }         
    }     
}   

I am trying to detect if there are any spaces, then I can simply take the next index. Could anyone tell me what I am doing wrong?

like image 959
farhana konka Avatar asked Nov 28 '22 01:11

farhana konka


2 Answers

String initials = "";
for (String s : fullname.split(" ")) {
  initials+=s.charAt(0);
}
System.out.println(initials);

This works this way :

  1. Declare a variable "initials" to hold the result
  2. Split the fullname string on space, and iterate on the single words
  3. Add to initials the first character of each word

EDIT :

As suggested, string concatenation is often not efficient, and StringBuilder is a better alternative if you are working on very long strings :

StringBuilder initials = new StringBuilder();
for (String s : fullname.split(" ")) {
  initials.append(s.charAt(0));
}
System.out.println(initials.toString());

EDIT :

You can obtain a String as an array of characters simply :

char[] characters = initials.toString().toCharArray();
like image 67
Simone Gianni Avatar answered Dec 04 '22 21:12

Simone Gianni


Try splitting by " " (space), then getting the charAt(0) (first character) of each word and printing it like this:

public static void main(String args[]) {
    String x = "Shojibur rahman";
    String[] myName = x.split(" ");
    for (int i = 0; i < myName.length; i++) {
        String s = myName[i];
        System.out.println(s.charAt(0));
    }
}
like image 44
brso05 Avatar answered Dec 04 '22 20:12

brso05