Reputation: 13120
When I grab the IP Address from my open socket, as someone has sent me a stream, I noticed that the IP has a forward-slash.
I just plan to simply omit it. But first I want to validate the first character in the string is the forward-slash:
String dataSource = data.getAddress().toString();
if(dataSource.substring(0,1) == "/"){
System.out.println("trailing forward slash, delete it ");
dataSource = dataSource.substring(1);
}
This IF statement isn't being detected.
Anyone see what I'm doing wrong?
Upvotes: 4
Views: 3898
Reputation: 2390
you should use .equals
for string comparrisons
so
if(dataSource.substring(0,1) == "/")
should be
if ("/".equals(dataSource.substring(0,1)))
Upvotes: 1
Reputation: 310859
Why use a String? You're just creating this problem for yourself. Use the datatype provided:
InetAddress dataSource = data.getInetAddress();
or
SocketAddress dataSource = data.getRemoteSocketAddress();
Then you have a semantically-aware .equals()
method in both cases.
Upvotes: 0
Reputation: 4425
String dataSource = "/hell";
if(dataSource.substring(0,1).equalsIgnoreCase("/")){
System.out.println("trailing forward slash, delete it ");
dataSource = dataSource.substring(1);
}
run this program. this is working..
Upvotes: 0
Reputation: 19185
Always use equals
when comparing values. Having said that you can just use indexOf
method for your purpose
if (dataSource.indexOf('/') == 0) {
dataSource = dataSource.substring(1);
}
Upvotes: 0
Reputation: 1852
If you want to test only, the first character , you can try the method,
dataSource.charAt(0)=='/'
Upvotes: 2
Reputation: 4441
Try this
if (("some string to check").equals(myString)){ doSomething(); }
Upvotes: 0
Reputation: 5276
You need to do dataSource.substring(0,1).equals("/")
, which actually checks the content of the strings. ==
only checks whether both sides are the same object.
Upvotes: 0
Reputation: 20741
please use .equals
if("/".equals(dataSource.substring(0,1))){
System.out.println("trailing forward slash, delete it ");
dataSource = dataSource.substring(1);
}
instead of ==
Upvotes: 2
Reputation: 1032
Use .equals(Object)
or .equalsIgnoreCase(String)
for comparing Strings.
Upvotes: 0
Reputation: 15644
For string comparisons use equals
method, as it is more reliable than using ==
operator (it compares the content while ==
comnpares the references ) :
Try using equals
method :
if(dataSource.substring(0,1).equals("/")){
Upvotes: 2
Reputation: 3332
You're comparing strings with ==
, which means you're checking to see if these two strings are literally the same string reference.
Use equal()
to check and see if two strings contain the same characters.
See: http://www.leepoint.net/notes-java/data/expressions/22compareobjects.html
Upvotes: 0