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.
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
You can use split and give it a maximum limit. ie: final_msg.split(":", 2)[0]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.