在 Java 中有一种方法可以检查条件:
“这个单个字符是否出现在字符串 x 中”
不使用循环?
String.contains()
检查字符串是否包含指定的 char 值序列String.indexOf()
它返回指定字符或子字符串第一次出现的字符串中的索引(此方法有 4 种变体)我不确定原始海报到底在问什么。由于 indexOf(...) 和 contains(...) 都可能在内部使用循环,也许他正在寻找如果没有循环这是否可能?我可以想到两种方法,一种当然是递归:
public boolean containsChar(String s, char search) {
if (s.length() == 0)
return false;
else
return s.charAt(0) == search || containsChar(s.substring(1), search);
}
另一个远没有那么优雅,但完整性......:
/**
* Works for strings of up to 5 characters
*/
public boolean containsChar(String s, char search) {
if (s.length() > 5) throw IllegalArgumentException();
try {
if (s.charAt(0) == search) return true;
if (s.charAt(1) == search) return true;
if (s.charAt(2) == search) return true;
if (s.charAt(3) == search) return true;
if (s.charAt(4) == search) return true;
} catch (IndexOutOfBoundsException e) {
// this should never happen...
return false;
}
return false;
}
当然,随着您需要支持越来越长的字符串,行数会增加。但是根本没有循环/递归。如果您担心 length() 使用循环,您甚至可以删除长度检查。
String temp = "abcdefghi";
if(temp.indexOf("b")!=-1)
{
System.out.println("there is 'b' in temp string");
}
else
{
System.out.println("there is no 'b' in temp string");
}
您可以使用String
类中的 2 种方法。
String.contains()
检查字符串是否包含指定的 char 值序列String.indexOf()
返回指定字符或子字符串第一次出现的字符串中的索引,如果未找到该字符,则返回 -1(此方法有 4 种变体)方法一:
String myString = "foobar";
if (myString.contains("x") {
// Do something.
}
方法二:
String myString = "foobar";
if (myString.indexOf("x") >= 0 {
// Do something.
}
链接:扎克·斯克里维纳
如果您需要经常检查相同的字符串,您可以预先计算出现的字符。这是一个使用包含在长数组中的位数组的实现:
public class FastCharacterInStringChecker implements Serializable {
private static final long serialVersionUID = 1L;
private final long[] l = new long[1024]; // 65536 / 64 = 1024
public FastCharacterInStringChecker(final String string) {
for (final char c: string.toCharArray()) {
final int index = c >> 6;
final int value = c - (index << 6);
l[index] |= 1L << value;
}
}
public boolean contains(final char c) {
final int index = c >> 6; // c / 64
final int value = c - (index << 6); // c - (index * 64)
return (l[index] & (1L << value)) != 0;
}}
要检查字符串中是否不存在某些内容,您至少需要查看字符串中的每个字符。因此,即使您没有明确使用循环,它也将具有相同的效率。话虽如此,您可以尝试使用 str.contains(""+char)。
是的,在字符串类上使用 indexOf() 方法。请参阅此方法的 API 文档
以下是您要查找的内容吗?
int index = string.indexOf(character);
return index != -1;
package com;
public class _index {
public static void main(String[] args) {
String s1="be proud to be an indian";
char ch=s1.charAt(s1.indexOf('e'));
int count = 0;
for(int i=0;i<s1.length();i++) {
if(s1.charAt(i)=='e'){
System.out.println("number of E:=="+ch);
count++;
}
}
System.out.println("Total count of E:=="+count);
}
}
如果你在 JAVA 中看到indexOf的源代码:
public int indexOf(int ch, int fromIndex) {
final int max = value.length;
if (fromIndex < 0) {
fromIndex = 0;
} else if (fromIndex >= max) {
// Note: fromIndex might be near -1>>>1.
return -1;
}
if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
// handle most cases here (ch is a BMP code point or a
// negative value (invalid code point))
final char[] value = this.value;
for (int i = fromIndex; i < max; i++) {
if (value[i] == ch) {
return i;
}
}
return -1;
} else {
return indexOfSupplementary(ch, fromIndex);
}
}
您可以看到它使用 for 循环来查找字符。请注意,您可能在代码中使用的每个indexOf都等于一个循环。
因此,对单个字符使用循环是不可避免的。
但是,如果您想找到具有更多不同形式的特殊字符串,请使用有用的库,例如util.regex
,它部署了更强大的算法来匹配字符或字符串模式与正则表达式。例如在字符串中查找电子邮件:
String regex = "^(.+)@(.+)$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(email);
如果您不喜欢使用正则表达式,只需使用一个循环charAt
并尝试在一个循环中涵盖所有情况。
小心递归方法比循环有更多的开销,所以不推荐。
String.contains(String)
或String.indexOf(String)
- 建议
"abc".contains("Z"); // false - correct
"zzzz".contains("Z"); // false - correct
"Z".contains("Z"); // true - correct
"and".contains(""); // true - correct
"and".contains(""); // false - correct
"and".indexOf(""); // 0 - correct
"and".indexOf(""); // -1 - correct
String.indexOf(int)
并仔细考虑String.indexOf(char)
与 charint
扩大
"and".indexOf("".charAt(0)); // 0 though incorrect usage has correct output due to portion of correct data
"and".indexOf("".charAt(0)); // 0 -- incorrect usage and ambiguous result
"and".indexOf("".codePointAt(0)); // -1 -- correct usage and correct output
char
或Character
视为单个字符吗?没有。在 unicode 字符的上下文中,char
或者Character
有时可以part of a single character
并且不应该被视为a complete single character
逻辑上的。
任何支持 Unicode 字符的字符编码的系统都应将 unicode 的代码点视为单个字符。
所以 Java 应该非常清晰和响亮地做到这一点,而不是向用户暴露太多的内部实现细节。
String
类不擅长抽象(尽管它需要令人困惑的大量 of understanding of its encapsulations to understand the abstraction
,因此需要 a anti-pattern
)。
char
用法有何不同?char
只能映射到基本多语言平面中的一个字符。
只能codePoint - int
覆盖 Unicode 字符的全部范围。
char
在内部被视为16-bit
无符号值,无法使用 UTF-16 内部表示法表示所有 unicode 字符,仅使用2-bytes
. 有时,16-bit
必须将某个范围内的值与另一个16-bit
值组合才能正确定义字符。
不用太冗长, , 和此类方法的用法indexOf
应该charAt
更加length
明确。真诚地希望 Java 将添加具有明确定义抽象的新类UnicodeString
。UnicodeCharacter
contains
和不喜欢的理由indexOf(int)
char
在 java 中。char
是不够的indexOf
中的转换掩盖了用户和用户可能会做的事情(除非用户知道确切的上下文)int
char
int
str.indexOf(someotherstr.charAt(0))
CharSequence
(aka String
) 更好 public static void main(String[] args) {
System.out.println("and".indexOf("".charAt(0))); // 0 though incorrect usage has correct output due to portion of correct data
System.out.println("and".indexOf("".charAt(0))); // 0 -- incorrect usage and ambiguous result
System.out.println("and".indexOf("".codePointAt(0))); // -1 -- correct usage and correct output
System.out.println("and".contains("")); // true - correct
System.out.println("and".contains("")); // false - correct
}
char
可以处理大部分实际用例。为了将来的可扩展性,在编程环境中使用代码点仍然更好。codepoint
应该处理几乎所有围绕编码的技术用例。codepoint
仍然超出了抽象级别的范围。char
接口。int
除非存储成本是唯一的指标,否则它仍然更好用codepoint
。此外,最好将存储视为byte
并将语义委托给围绕存储构建的业务逻辑。codepoint
应该成为最低级别的接口,并且可以codepoint
在运行时环境中构建其他语义。static String removeOccurences(String a, String b)
{
StringBuilder s2 = new StringBuilder(a);
for(int i=0;i<b.length();i++){
char ch = b.charAt(i);
System.out.println(ch+" first index"+a.indexOf(ch));
int lastind = a.lastIndexOf(ch);
for(int k=new String(s2).indexOf(ch);k > 0;k=new String(s2).indexOf(ch)){
if(s2.charAt(k) == ch){
s2.deleteCharAt(k);
System.out.println("val of s2 : "+s2.toString());
}
}
}
System.out.println(s1.toString());
return (s1.toString());
}
you can use this code. It will check the char is present or not. If it is present then the return value is >= 0 otherwise it's -1. Here I am printing alphabets that is not present in the input.
import java.util.Scanner;
public class Test {
public static void letters()
{
System.out.println("Enter input char");
Scanner sc = new Scanner(System.in);
String input = sc.next();
System.out.println("Output : ");
for (char alphabet = 'A'; alphabet <= 'Z'; alphabet++) {
if(input.toUpperCase().indexOf(alphabet) < 0)
System.out.print(alphabet + " ");
}
}
public static void main(String[] args) {
letters();
}
}
//Ouput Example
Enter input char
nandu
Output :
B C E F G H I J K L M O P Q R S T V W X Y Z
您将无法检查 char 是否出现在某个字符串中,而无需使用循环/递归至少遍历字符串一次(诸如 indexOf 的内置方法也使用循环)
如果没有。如果字符在字符串x中,您查找的次数比我建议使用Set数据结构的字符串长度要多得多,因为这比简单地使用更有效indexOf
String s = "abc";
// Build a set so we can check if character exists in constant time O(1)
Set<Character> set = new HashSet<>();
int len = s.length();
for(int i = 0; i < len; i++) set.add(s.charAt(i));
// Now we can check without the need of a loop
// contains method of set doesn't use a loop unlike string's contains method
set.contains('a') // true
set.contains('z') // false
使用 set 您将能够在恒定时间O(1) 中检查字符串中是否存在字符,但您还将使用额外的内存(空间复杂度将为 O(n) )。