6

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?

farhana konka
  • 81
  • 1
  • 2
  • 8
  • I know this isn't your problem, but `myName[i] == ""` is bad in two ways. 1.) You are using `==` to compare `String`s, which is erroneous. 2.) Instead of comparing a `String` with `""`, use the `isEmpty()` method of `String`. – bcsb1001 Oct 03 '14 at 16:38

11 Answers11

16
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();
Simone Gianni
  • 11,426
  • 40
  • 49
7

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));
    }
}
bcsb1001
  • 2,834
  • 3
  • 24
  • 35
brso05
  • 13,142
  • 2
  • 21
  • 40
5

With Java 8 streams:

String initials = Arrays.stream(str.split(" "))
    .map(s -> s.substring(0, 1))
    .collect(Collectors.joining());
System.out.println(initials);
Jeffrey Bosboom
  • 13,313
  • 16
  • 79
  • 92
3

If you are using kotlin then you can use below code for get initial charactor

 val myName = name.split(" ")
 val initial = myName.fold("", { acc, s -> acc + s[0] })
 print(initial)
Prashant Jajal
  • 3,469
  • 5
  • 24
  • 38
3

Surprised that nobody mentioned about making use of an already available library. One can use here WordUtils form apache commons-text

String name = "My Name";
String initials = WordUtils.initials(name);
System.out.println(initials);  // Outputs:  MN
Lokesh
  • 557
  • 4
  • 13
2

There are a number of errors in your code:

String [] myName=x.split("");

Did you really want to split on "" (empty string)? You probably wanted to split on spaces:

String [] myName=x.split(" ");

And:

if(myName[i]=="")

Never compare strings with == in Java, always use .equals:

if (myName[i].equals(""))
Jesper
  • 202,709
  • 46
  • 318
  • 350
1

You need to spilt it with a space you cannot split with "". It doesn't mean anything. Another thing you did wrong was === in string comparison that is not correct. Please refer to How do I compare strings in Java?

public class q4 {
   public static void main(String args[])
   {
       String x="Shojibur rahman";
       String [] myName=x.split(" ");
       for(int i=0; i<myName.length; i++)
       {
           if(!myName[i].equals(""))
           {
               System.out.println(myName[i]);
           }               
       }          
   }     
}
Community
  • 1
  • 1
StackFlowed
  • 6,664
  • 1
  • 29
  • 45
1

You are splitting on an empty string not a space " ". Your loops don't really make much sense either, I'm not sure what you are trying to do.

   String [] myName=x.split(" ");
   for(int i=0; i<myName.length; i++)
   {
       if (!myName[i].isEmpty()) {
          System.out.println(myName[i].charAt(0));
       }              
   }          
Tim B
  • 40,716
  • 16
  • 83
  • 128
1

Since you don't have thread-safe with your program, you could use StringBuilder. For the long string, i recommand you could use StringTokenizer.

Jake Huang
  • 140
  • 1
  • 12
  • 1.) Doesn't answer the question 2.) Never use `StringBuffer`, unless you have a _very_ good reason to 3.) As said in the [`StringTokenizer` docs](http://docs.oracle.com/javase/8/docs/api/java/util/StringTokenizer.html), its use is discouraged in code. – bcsb1001 Oct 03 '14 at 16:40
  • 1
    Sorry, it should be `StringBuilder`. Thank you to let me know, i didn't read StringTokenizer Api carefully. – Jake Huang Oct 03 '14 at 16:48
1

The accepted reply in Java 8:

/**
 * Gets the first character of every word in the sentence.
 *
 * @param string
 * @return
 */
public static String getFirstLetterFromEachWordInSentence(final String string) {
    if (string == null) {
        return null;
    }
    StringBuilder sb = new StringBuilder();
    Arrays.asList(string.split(" ")).forEach(s -> sb.append(s.charAt(0)).append(" "));
    return sb.toString().trim();
}
1

The split method written above is working fine but will cause error when:

  1. String first word of start with space
  2. And, if string have more than one space between words

Above written situation can occur when you are getting the value from user, In this scenario you can use :-

    String SubName = "input text provided by user"
    String initialsOfSubName = "";
    boolean v = true;
    for (int i = 0; i < SubName.length(); i++) {
        // If it is space, set v as true.
        if (SubName.charAt(i) == ' ')
            v = true;
        else if (SubName.charAt(i) != ' ' && v == true) {
            initialsOfSubName += (SubName.charAt(i));
            // on the place of string you can store it in an, array or list;
            v = false;
        }
    }
    Log.d("testRegex",initialsOfSubName);
PRANAV SINGH
  • 1,000
  • 11
  • 17