¿Cómo puedo comprobar si aparece un solo carácter en una cadena?


En Java hay una manera de comprobar la condición:

"¿Aparece este carácter único en la cadena x "

¿Sin usando un bucle?

Author: ArjunShankar, 2009-02-03

15 answers

Puede utilizar string.indexOf('a').

Si el 'a' está presente en string, devuelve el índice(>=0). Si no, devuelve -1. Por lo tanto, un valor de retorno no negativo significa que '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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-03 22:27:34
  • String.contains() que comprueba si la cadena contiene una secuencia especificada de valores char
  • String.indexOf() que devuelve el índice dentro de la cadena de la primera ocurrencia del carácter o subcadena especificada (hay 4 variaciones de este método)
 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-02-03 06:56:00

No estoy seguro de lo que el póster original está pidiendo exactamente. Since indexOf(...) y contiene(...) ambos probablemente utilizan bucles internamente, tal vez él está buscando para ver si esto es posible en absoluto sin un bucle? Puedo pensar en dos formas de mano, una sería, por supuesto, la recurrencia:

public boolean containsChar(String s, char search) {
    if (s.length() == 0)
        return false;
    else
        return s.charAt(0) == search || containsChar(s.substring(1), search);
}

El otro es mucho menos elegante, pero completo...:

/**
 * 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;
}

El número de líneas crece a medida que necesita soportar cadenas más y más largas, por supuesto. Pero no hay bucles / recurrencias en todo. Incluso puedes eliminar la comprobación de longitud si te preocupa que length () use un bucle.

 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-07-11 07:00:51

Para comprobar si algo no existe en una cadena, al menos necesita mirar cada carácter en una cadena. Así que incluso si no usas explícitamente un bucle, tendrá la misma eficiencia. Dicho esto, puede intentar usar str.contiene(""+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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-02-03 05:41:44

Si necesita comprobar la misma cadena a menudo, puede calcular las ocurrencias de caracteres por adelantado. Esta es una implementación que utiliza una matriz de bits contenida en una matriz larga:

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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-05-07 11:16:01

Sí, usando el método indexOf() en la clase string. Consulte la documentación de la API para este método

 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-27 04:40:43

Puede usar 2 métodos de la clase String.

  • String.contains() que comprueba si la cadena contiene una secuencia especificada de valores char
  • String.indexOf() que devuelve el índice dentro de la cadena de la primera ocurrencia del carácter o subcadena especificada o devuelve -1 si el carácter no se encuentra (hay 4 variaciones de este método)

Método 1:

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

Método 2:

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

Enlaces por: 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
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'");

Salida

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/ajaxhispano.com/template/agent.layouts/content.php on line 61
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/ajaxhispano.com/template/agent.layouts/content.php on line 61
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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-09 06:05:34

¿Es lo siguiente lo que estabas buscando?

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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-27 13:20:16

Usé la cadena.método includes () para esto que devuelve true o false si se encuentra la cadena o el carácter. Consulte la documentación a continuación.

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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-28 02:37:30

//esto es solo lo principal... puede utilizar el lector o escáner con búfer wither

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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-11 03:49:13