John Doe
John Doe

Reputation: 41

String/Array in Java

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++)
    {

    }

Upvotes: 1

Views: 89

Answers (3)

EarlGrey
EarlGrey

Reputation: 531

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.

Upvotes: 1

brso05
brso05

Reputation: 13222

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.

Upvotes: 1

TheLostMind
TheLostMind

Reputation: 36304

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

Upvotes: 2

Related Questions