views:

119

answers:

2

Hello everyone,

I am designing a chat applet. In this, a user will append his name to the beginning of the message that he sends to the other user. In the window of other user, I want to retrieve the appended user name from that string. How do I do that? The message sent by the user is as follows :

final_msg = user_name + ": " + user_message

Hence I want to know how to retrieve the user_name string only. Is there a function that can retrieve a substring upto the first ":"? I dont want to use final_msg.split(":"), because there is a possiblity that the user_message contains ":", which will then give me an array of strings.

+8  A: 

Quick tip:

use indexOf method to find first index of ':' character, then do a substring() call.

String userName = final_msg.substring(0,final_msg.indexOf(':'));

Edit: Consider renaming your variable from final_msg to finalMsg - just because, that is the Java style. Normally "_" appear in Java Constant names

ring bearer
Speaking of variable names... you put `s` where I assume you meant `final_msg`
R. Bemrose
Good catch, edited :) and +1
ring bearer
+5  A: 

You can use split and give it a maximum limit. ie: final_msg.split(":", 2)[0]

Milan Ramaiya
+1: That's a very good suggestion as it is easy to get right.
Donal Fellows
This is much easier than the other suggestion. Not to mention easier to read later.
Joel