开发者

Finding a / symbol in string

I'm trying to find a forward slash in a string...

This doesn't seem to work:

if ("/test".indexOf("/") > -1) {

What am I doing wrong?

Funny thing is... I tried this:

if 开发者_如何学C("!test".indexOf("!") > -1) {

and it works! I also tried \/ for that... help?


Use contains

if("/test".contains("/"))

However both of your methods should work and both did work in my tests.


Your say.getText() call is probably returning a string that doesn't start with /.
(See comment)

For example, it might be starting with (U+2215 DIVISION SLASH), or with a space (or with a \ backslash).

EDIT: You have whitespace or a non-printing character before the /.         Trust me.


There must be something else.

 public static void main(String[] args)
 {
        System.out.println("!test".indexOf("!"));
        System.out.println("/test".indexOf("/"));
 }

This correctly prints

0
0


To test if a String starts with a given character, use charAt(0) to get that charracter

    if (text.charAt(0) == '/') {

or startsWith(String) to check for more than one character (a String)

    if (text.startsWith("/kick ")) {

EDIT:
use trim() to delete leading and trailing spaces if needed:

    if (text.trim().charAt(0) == '/') {
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜