Jak mogę sprawdzić, czy pojedynczy znak pojawia się w łańcuchu?

W Javie jest sposób na sprawdzenie warunku:

"Czy ten pojedynczy znak pojawia się w ogóle w łańcuchu x"

Bez użycia pętli?

Author: ArjunShankar, 2009-02-03

15 answers

Możesz użyć string.indexOf('a').

Jeśli 'a' jest obecny w string, zwraca indeks(>=0). Jeśli nie, zwraca -1. Zatem nieujemna wartość zwracana oznacza, że 'a' is present in the string.

 208
Author: mP.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-03 22:27:34
  • String.contains() która sprawdza, czy łańcuch znaków zawiera określoną sekwencję wartości znaku
  • String.indexOf() która zwraca indeks w ciągu pierwszego wystąpienia określonego znaku lub podłańcucha (są 4 warianty tej metody)
 128
Author: Zach Scrivena,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-02-03 06:56:00

Nie jestem pewien, o co dokładnie pyta oryginalny plakat. Od indexOf(...) i zawiera(...) oba prawdopodobnie używają pętli wewnętrznie, może chce sprawdzić, czy jest to w ogóle możliwe bez pętli? Mogę wymyślić dwa sposoby poza ręką, jedną z nich byłaby oczywiście rekurencja:

public boolean containsChar(String s, char search) {
    if (s.length() == 0)
        return false;
    else
        return s.charAt(0) == search || containsChar(s.substring(1), search);
}
Druga jest znacznie mniej elegancka, ale kompletna...:
/**
 * 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;
}

Liczba linii rośnie, ponieważ musisz oczywiście obsługiwać dłuższe i dłuższe ciągi. Ale nie ma pętli / rekurencji w wszystkie. Możesz nawet usunąć length check, jeśli obawiasz się, że ta długość() używa pętli.

 28
Author: Jack Leow,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-02-03 13:53:56
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");
}
 12
Author: Richard,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-07-11 07:00:51

Aby sprawdzić, czy coś nie istnieje w łańcuchu, musisz przynajmniej spojrzeć na każdy znak w łańcuchu. Więc nawet jeśli nie użyjesz jawnie pętli, będzie ona miała taką samą wydajność. Biorąc to pod uwagę, możesz spróbować użyć str.contains (""+char).

 3
Author: mweiss,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-02-03 05:41:44

Jeśli chcesz często sprawdzać ten sam ciąg znaków, możesz obliczyć wystąpienia znaków z góry. Jest to implementacja, która używa tablicy bitowej zawartej w długiej tablicy:

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;
}}
 3
Author: fillumina,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-05-07 11:16:01

Tak, używając metody indexOf () na klasie string. zobacz dokumentację API dla tej metody

 2
Author: Mystic,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-02-03 05:44:38
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);
    }
}
 1
Author: Praveen kumar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-11-27 04:40:43

Możesz użyć 2 metod z klasy String.

  • String.contains() która sprawdza, czy łańcuch znaków zawiera określoną sekwencję wartości znaku
  • String.indexOf() która zwraca indeks w ciągu pierwszego wystąpienia określonego znaku lub podłańcucha lub zwraca -1 jeżeli znak nie został znaleziony (są 4 warianty tej metody)

Metoda 1:

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

Metoda 2:

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

Links by: Zach Scrivena

 1
Author: Halfacht,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-27 13:14:16
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'");

Wyjście

string does not contains the char 's'
 0
Author: praveen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-10-05 07:27:00
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());
}
 0
Author: Ganeshmani,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-05-22 05:21:00
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
 0
Author: Nandu cg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-09 06:05:34

Czy poniżej tego, czego szukałeś?

int index = string.indexOf(character);
return index != -1 && string.lastIndexOf(character) != index;
 0
Author: Toochka,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-27 13:20:16

Użyłem Sznurka.metoda includes (), która zwraca true lub false, jeśli łańcuch lub znak został znaleziony. Zobacz poniższą dokumentację.

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

 -1
Author: Udugam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-28 02:37:30

/ / to jest tylko główne... możesz użyć czytnika buforowanego wither lub skanera

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... 
 -4
Author: anytime,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-01-11 03:49:13