Pregunta

¿Cómo puedo comprobar para ver si una cadena contiene un carácter de espacio en blanco, un espacio vacío o "". Si es posible, proporcione un ejemplo de Java.

Por ejemplo: String = "test word";

¿Fue útil?

Solución

Para comprobar si una cadena contiene espacios en blanco utilizar un Matcher y lo llaman de método de búsqueda.

Pattern pattern = Pattern.compile("\\s");
Matcher matcher = pattern.matcher(s);
boolean found = matcher.find();

Si desea comprobar si sólo se compone de espacios en blanco a continuación, puede utilizar String.matches :

boolean isWhitespace = s.matches("^\\s*$");

Otros consejos

Comprobar si una cadena contiene al menos un carácter de espacio en blanco:

public static boolean containsWhiteSpace(final String testCode){
    if(testCode != null){
        for(int i = 0; i < testCode.length(); i++){
            if(Character.isWhitespace(testCode.charAt(i))){
                return true;
            }
        }
    }
    return false;
}

Referencia:


El uso de la biblioteca guayaba , es mucho más simple:

return CharMatcher.WHITESPACE.matchesAnyOf(testCode);

CharMatcher.WHITESPACE es también una gran cantidad más a fondo cuando se trata de soporte Unicode.

Esto le dirá si hay cualquier espacios en blanco:

Ya sea por un bucle:

for (char c : s.toCharArray()) {
    if (Character.isWhitespace(c)) {
       return true;
    }
}

o

s.matches(".*\\s+.*")

Y StringUtils.isBlank(s) le dirá si hay solamente whitepsaces.

Use Apache Commons StringUtils :

StringUtils.containsWhitespace(str)

El uso de este código, era mejor solución para mí.

public static boolean containsWhiteSpace(String line){
    boolean space= false; 
    if(line != null){


        for(int i = 0; i < line.length(); i++){

            if(line.charAt(i) == ' '){
            space= true;
            }

        }
    }
    return space;
}
public static void main(String[] args) {
    System.out.println("test word".contains(" "));
}

Se podría utilizar expresiones regulares para determinar si hay un espacio en blanco. \s.

Más información de expresiones regulares aquí .

import java.util.Scanner;
public class camelCase {

public static void main(String[] args)
{
    Scanner user_input=new Scanner(System.in);
    String Line1;
    Line1 = user_input.nextLine();
    int j=1;
    //Now Read each word from the Line and convert it to Camel Case

    String result = "", result1 = "";
    for (int i = 0; i < Line1.length(); i++) {
        String next = Line1.substring(i, i + 1);
        System.out.println(next + "  i Value:" + i + "  j Value:" + j);
        if (i == 0 | j == 1 )
        {
            result += next.toUpperCase();
        } else {
            result += next.toLowerCase();
        }

        if (Character.isWhitespace(Line1.charAt(i)) == true)
        {
            j=1;
        }
        else
        {
            j=0;
        }
    }
    System.out.println(result);

Use org.apache.commons.lang.StringUtils.

  1. para buscar espacios en blanco
  

boolean withWhiteSpace = StringUtils.contains ( "mi nombre", " ");

  1. Para eliminar todos los espacios en blanco en una cadena
  

StringUtils.deleteWhitespace (null) = null   StringUtils.deleteWhitespace ( "") = ""   StringUtils.deleteWhitespace ( "abc") = "abc"   StringUtils.deleteWhitespace ( "ab c") = "abc"

String str = "Test Word";
            if(str.indexOf(' ') != -1){
                return true;
            } else{
                return false;
            }

Me propósito de que un método muy simple que utilizan String.contains :

public static boolean containWhitespace(String value) {
    return value.contains(" ");
}

Un poco Ejemplo de uso:

public static void main(String[] args) {
    System.out.println(containWhitespace("i love potatoes"));
    System.out.println(containWhitespace("butihatewhitespaces"));
}

Salida:

true
false

Usted puede hacer básicamente esto

if(s.charAt(i)==32){
   return true;
}

Debe escribir booleano carbón method.Whitespace es 32.

Se puede usar Chatat () función para averiguar espacios en cadena.

 public class Test {
  public static void main(String args[]) {
   String fav="Hi Testing  12 3";
   int counter=0;
   for( int i=0; i<fav.length(); i++ ) {
    if(fav.charAt(i) == ' ' ) {
     counter++;
      }
     }
    System.out.println("Number of spaces "+ counter);
    //This will print Number of spaces 4
   }
  }
package com.test;

public class Test {

    public static void main(String[] args) {

        String str = "TestCode ";
        if (str.indexOf(" ") > -1) {
            System.out.println("Yes");
        } else {
            System.out.println("Noo");
        }
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top