繁体   English   中英

如何检查单个字符是否出现在字符串中?

[英]How can I check if a single character appears in a string?

在 Java 中有没有办法检查条件:

“这个单个字符是否出现在字符串 x 中”

使用循环?

您可以使用string.indexOf('a')

如果string存在字符a

它返回此对象表示的字符序列中该字符第一次出现的索引,如果该字符没有出现,则返回 -1。

  • String.contains()检查字符串是否包含指定的字符值序列
  • 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()检查字符串是否包含指定的字符值序列
  • String.indexOf()返回指定字符或子字符串第一次出现的字符串中的索引,如果未找到该字符则返回 -1(此方法有 4 种变体)

方法一:

String myString = "foobar";
if (myString.contains("x") {
    // Do something.
}

方法二:

String myString = "foobar";
if (myString.indexOf("x") >= 0 {
    // Do something.
}

链接: Zach Scrivena

如果您需要经常检查相同的字符串,您可以预先计算字符出现次数。 这是一个使用包含在长数组中的位数组的实现:

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 文档

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);
    }
}

下面是你要找的吗?

int index = string.indexOf(character);
return index != -1;

如果看到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)与 char 到int加宽

"😀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

Java 世界中关于字符的讨论是模棱两可的

charCharacter的值可以视为单个字符吗?

没有 在 unicode 字符的上下文中, charCharacter有时可以part of a single character并且在逻辑上不应被视为a complete single character

如果不是,应该将什么视为单个字符(逻辑上)?

任何支持 Unicode 字符的字符编码的系统都应将 unicode 的代码点视为单个字符。

因此,Java 应该非常清楚和响亮地做到这一点,而不是将过多的内部实现细节暴露给用户。

String类不擅长抽象(尽管它需要understanding of its encapsulations to understand the abstraction 😒😒😒大量令人困惑的understanding of its encapsulations to understand the abstraction 😒😒😒 ,因此是一个anti-pattern )。

它与一般的char用法有何不同?

char只能映射到基本多语言平面中的字符。

只有codePoint - int可以覆盖整个 Unicode 字符范围。

为什么会有这种差异?

char在内部被视为16-bit无符号值,并且无法使用 UTF-16 内部表示形式表示所有 unicode 字符,仅使用2-bytes 有时,必须将16-bit范围内的值与另一个16-bit值组合才能正确定义字符。

不用太冗长, indexOfcharAtlength等方法的用法应该更明确。 真诚地希望 Java 将添加具有明确定义的抽象的新UnicodeStringUnicodeCharacter类。

更喜欢contains而不是indexOf(int)

  1. 实际上,有许多代码流将 Java 中的逻辑字符视为char
  2. 在 Unicode 上下文中, char是不够的
  3. 虽然indexOf接受一个int ,但charint转换会屏蔽用户,用户可能会做类似str.indexOf(someotherstr.charAt(0))事情(除非用户知道确切的上下文)
  4. 因此,将所有内容都视为CharSequence (又名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
    }

语义

  1. char可以处理大多数实际用例。 为了将来的可扩展性,在编程环境中使用代码点仍然更好。
  2. codepoint应该处理几乎所有围绕编码的技术用例。
  3. 尽管如此, Grapheme Clusters 不属于codepoint抽象级别的范围。
  4. 如果int成本太高(加倍),存储层可以选择char接口。 除非存储成本是唯一的指标,否则最好使用codepoint 此外,最好将存储视为byte并将语义委托给围绕存储构建的业务逻辑。
  5. 语义可以在多个级别进行抽象。 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

一个人用这个怎么样?

let text = "Hello world, welcome to the universe.";
let result = text.includes("world");
console.log(result) ....// true

结果将是truefalse

这总是对我有用

String s="praveen";
boolean p=s.contains("s");
if(p)
    System.out.println("string contains the char 's'");
else
    System.out.println("string does not contains the char 's'");

产量

string does not contains the char 's'

您将无法检查 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) )。

我使用string.includes()方法,如果找到字符串或字符,则返回true或false。 请参阅以下文档。

https://www.w3schools.com/jsref/jsref_includes.asp

//这只是主要...你可以使用枯萎的缓冲读卡器或扫描仪

string s;
int l=s.length();
int f=0;
for(int i=0;i<l;i++)
   {
      char ch1=s.charAt(i); 
      for(int j=0;j<l;j++)
         {
          char ch2=charAt(j);
          if(ch1==ch2)
           {
             f=f+1;
             s.replace(ch2,'');
           }
          f=0;
          }
     }
//if replacing with null does not work then make it space by using ' ' and add a if condition on top.. checking if its space if not then only perform the inner loop... 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM