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
Finding a / symbol in string
提问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
回答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) == '/') {

