Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to retrieve part of a string in java?

Tags:

java

string

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.

like image 831
mithun1538 Avatar asked Apr 05 '10 17:04

mithun1538


1 Answers

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

like image 184
ring bearer Avatar answered Oct 12 '22 23:10

ring bearer