Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java-如何在字符串中查找非字母?(捷径)_Java_String_Indexof_Lastindexof - Fatal编程技术网

Java-如何在字符串中查找非字母?(捷径)

Java-如何在字符串中查找非字母?(捷径),java,string,indexof,lastindexof,Java,String,Indexof,Lastindexof,在Java中,给定一个字符串,如“abc@df其中字符“@”可以是任何其他非字母,如“%”、“^”和“&”等。查找该索引的最有效方法是什么?我知道for循环有点快(取决于字符串长度),但是其他更快的方法呢?一种查找所有非字母索引或最接近给定索引的索引(如indexOf(string,startingIdx))的方法 谢谢 您可能应该使用正则表达式: Pattern patt = Pattern.compile("[^A-Za-z]"); Matcher mat = patt.matche

在Java中,给定一个字符串,如“abc@df其中字符“@”可以是任何其他非字母,如“%”、“^”和“&”等。查找该索引的最有效方法是什么?我知道for循环有点快(取决于字符串长度),但是其他更快的方法呢?一种查找所有非字母索引或最接近给定索引的索引(如indexOf(string,startingIdx))的方法
谢谢

您可能应该使用正则表达式:

  Pattern patt = Pattern.compile("[^A-Za-z]");
  Matcher mat = patt.matcher("avc@dgh");
  boolean found = mat.find();
  System.out.println(found ? mat.start() : -1);

对于for循环,可以使用Character类确定每个字符是否为字母(或其他类型)。请参阅:

如果您查看indexOf的实现,我敢打赌您会找到一个循环。使用它的好处是您不必编写循环,这是一件好事,因为最好的代码是您不编写的代码。@Bill我想我没有澄清。找到一种查找非字母字符索引的方法。由于存在大量非字母字符,因此不可能使用indexOf(),因为您不知道要查找的字符。希望这有帮助!我当然明白了,这也是我留下评论而不是建议答案的部分原因。