java 在字符串中查找 / 符号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3576930/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 02:29:57  来源:igfitidea点击:

Finding a / symbol in string

java

提问by test

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 ("!test".indexOf("!") > -1) {

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

它有效!我也试过 \/ 那个......帮助?

回答by Adam

Use contains

使用包含

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

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

但是,您的两种方法都应该有效,并且都在我的测试中有效。

回答by SLaks

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

您的say.getText()呼叫可能返回一个不以/.
(见评论)

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

例如,它可能以(U+2215 DIVISION SLASH)开头,或以空格(或\反斜杠)开头。

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

编辑:你有空白或者非打印字符/。         相信我

回答by gawi

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

回答by user85421

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

要测试字符串是否以给定字符开头,请使用charAt(0)获取该字符

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

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

startsWith(String)检查多个字符(字符串)

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

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

编辑:
使用trim()删除领先的,如果需要尾随空格:

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