1

Does this work? I'm trying to print a message in this.

char[] tempMessage = message.toCharArray();     
    String[] message2 = message.split(" ");          
    Integer.toString(number).toCharArray(); 
    for(int x = 0; x<newMessage.length; x++)
    {

    }
1
  • 1
    how should punctuation be treated? Should "Hello, world!!" output "H5w5" or "h6w7"? Perhaps we should be splitting on word boundaries, not white space. Commented Sep 15, 2014 at 14:25

3 Answers 3

2

Although its better to use a StringBuilder, I can show it using String(s).

String[] strArr = "hello world".split("\\s+");
String s = String.valueOf(strArr[0].charAt(0))+strArr[0].length()+String.valueOf(strArr[1].charAt(0))+strArr[1].length();

Output : h5w5
Sign up to request clarification or add additional context in comments.

Comments

1
String[] message2 = message.split("\\s+");
String output = "";
for(int i = 0; i < message2.length; i++)
{
    output += "" + message2[i].charAt(0) + message2[i].length();
}
//output has output string.

Comments

1

TheLostMind's solution is already good, but I think it needs a solution for Strings of arbitrary length.

String outputString = "";
for(String x : message.split("\\s+"))
{
  outputString = outputString.concat(x.charAt(0) + x.length());
}

As stated in the comments, this solution is very similiar to brso05's solution. The difference is in using the :-Operator in the for-loop. It's shorter and IMHO easier to understand, as it says 'for each String in the resulting array'.
Also, using the concat()-function is considered safer in my work environment.

1 Comment

@brso05 I'm sorry, started typing before you posted. Still, it's different from yours and needs one line less.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.