0

Suppose I have a string like:

"  Hello Word  "

How do I get the acronym "HW" excluding the leading and trailing spaces?

I tried it with looping constructs. But I want to do it without using any for loops or split method.

Additional from OP in comments:
I just want to get the first letter of every word in the string, irrespective of case. If the string is " jon snow ", I want the result as "JS"

Makyen
  • 27,758
  • 11
  • 68
  • 106
Ishtiaq
  • 71
  • 1
  • 11
  • 2
    So you want to remove any character which isn't an upper-case character? Consider a regex... – Jon Skeet Sep 06 '15 at 07:30
  • 1
    No. I just want to get the first letter of every word in the string, irrespective of case. If the string is " jon snow ", I want the result as "JS" – Ishtiaq Sep 06 '15 at 07:32
  • 1
    Try this (last one maybe?) : http://stackoverflow.com/questions/26180992/get-the-first-character-of-each-word-in-a-string – FreudianSlip Sep 06 '15 at 07:33
  • 4
    Why no looping constructs? Even if you use other operations without looping explicitly, those will loop (e.g. regex). – ash Sep 06 '15 at 07:38
  • I have a feeling this is an interview question. You know, to see how resourceful the candidate is. When they come up with a loop, the interviewer says "No, no loops". Then the candidate submits a solution with a regex, and the interviewer says "No regexes either" etc. – Mr Lister Sep 06 '15 at 07:55
  • 1
    @Ishtiaq, please update your question to include that information about wanting to get the first letter of every word **even if it's lowercase**. – Pedro Pinheiro Sep 06 '15 at 07:56
  • `String result = x.replaceAll("[a-z ]", "").toUpperCase();` – SaviNuclear Sep 06 '15 at 07:59
  • 2
    @PedroPinheiro That is generally what acronym means. – Andreas Sep 06 '15 at 07:59

6 Answers6

9

You can use a regex, but note that regular expression processing does include an internal loop.

The following will leave only letters which are at the beginning of a word, and then convert them to upper case:

    String str = " hello World 18 times ";
    String result = str.replaceAll("\\B.|\\P{L}", "").toUpperCase();

The result here is "HWT".

It removes every character which is not on a word boundary on its left, as well as any character which is not a letter (this will take care of spaces). The result is converted to uppercase.

RealSkeptic
  • 32,074
  • 7
  • 48
  • 75
  • 1
    RealSkeptic, while your answer is correct; the solution and the means to how he framed this question are extremely esoteric. We shouldn't propagate his want of solving this with a regex that maybe 2% of engineers can understand. We should provide him with a general, best practices approach, something which is more commonly used in the industry. – Devarsh Desai Sep 06 '15 at 07:57
  • Best answer. It should be accepted. – Hanzallah Afgan Sep 06 '15 at 07:58
  • `String result = x.replaceAll("[a-z ]", "").toUpperCase();` this also work fine – SaviNuclear Sep 06 '15 at 07:58
  • @SaviNuclear The user asked for the letters at the beginning of each word, not for the uppercase letters in the string. It's in a comment on the question. – RealSkeptic Sep 06 '15 at 08:00
  • @DevarshDesai I disagree. The question may be esoteric, but that doesn't make the question or this answer "off-topic" for Stack Overflow. It is a great answer for the constraints given in the question. Your comment may be good for the question, not for this answer. – Andreas Sep 06 '15 at 08:02
  • Hey Andreas, I never said the question or this answer is off topic; I think @RealSkeptic's answer is very clever! At the same time, there is a strong divide between pragmatism and being esoteric; this question's requirements are very unusual, and as members of a community who teach, i think it would be better for the question-er to understand **why** using the split() method and a for loop is better for: code readability, communication, matainability, and why his requirements are really arbitrary (as mentioned regex itself uses a loop). – Devarsh Desai Sep 06 '15 at 08:07
  • @RealSkeptic what about if we want a space in between them? if The result should be H W T..how to do it? – Noufal Aug 22 '16 at 11:48
1

If you have a choice to use apache lib then please visit the below link http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/text/WordUtils.html#initials(java.lang.String).

Before using the regex that mentioned above the go through the complexity of both options. Moreover if apache lib suits you then need not to rotate the wheel again for the same situation use apache lib.

Note: Internally/Externally every algorithm traverse the complete string.

prasingh
  • 311
  • 3
  • 14
0

Use WordUtils if you have it, otherwise, with Java 8 you can do the following without loops (although it does have a split):

String word = " Hello World ";
String result = Arrays.stream(word.trim().split(" "))
        .map(word -> word.charAt(0))
        .map(c -> c.toString().toUpperCase())
        .collect(Collectors.joining());
Graham Russell
  • 798
  • 12
  • 20
-2
String [] tokens = "Hello World".split("[\\W]");
String newString = "";
for(String s:tokens){
    newString += s.charAt(0);
}
System.out.println("Acronym - " + newString);

New Answer without loops -

String[] acronym = myString.split("(?<=[\\S])[\\S]*\\s*");
Raman Shrivastava
  • 2,827
  • 12
  • 25
-2

Use Java default Tokenizer method. Tokenize the string and get the character at the first index of the token. Hope this will help

StringTokenizer defaultTokenizer = new StringTokenizer(str);
while (defaultTokenizer.hasMoreTokens())
{
    //get first letter of a token here
    defaultTokenizer.nextToken(); // will get u next token
}
Hammad Raza
  • 1,875
  • 1
  • 8
  • 11
  • 1
    The documentation of the `StringTokenizer` class says: *"`StringTokenizer` is a legacy class that is retained for compatibility reasons although its use is discouraged in new code."* – RealSkeptic Sep 06 '15 at 07:43
  • This is the only answer that doesn't use `for` or `split` though. – Mr Lister Sep 06 '15 at 07:51
-2

Just try this:-

package com.test.servlet;
import java.io.IOException;
public class A1 {

    public static void main(String args[])throws IOException
    {
        String x = "Satvir Kumar Singh ";
        int c1;
          String result = x.replaceAll("[a-z ]", "").toUpperCase();
          System.out.println(result);
        /*for (int i = 0; i < x.length(); i++) {
            c1 = (int) x.charAt(i); 
            if(c1>=65 && c1<=96){
                System.out.print(x.charAt(i));
            }
        }*/
    }   
}

You can try this then.

SaviNuclear
  • 882
  • 6
  • 19
  • OP mentioned in a comment that he want "first letter of every word in the string, irrespective of case". – Andreas Sep 06 '15 at 08:35