Domanda

Come posso controllare per vedere se una stringa contiene un carattere di spazio, uno spazio vuoto o "". Se possibile, si prega di fornire un esempio di Java.

Ad esempio: String = "test word";

È stato utile?

Soluzione

Per controllare se una stringa contiene spazi usare un Matcher e chiamare di metodo find.

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

Se si desidera verificare se consiste solo di spazi bianchi , è possibile utilizzare String.matches :

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

Altri suggerimenti

Verificare se una stringa contiene almeno un carattere di spazio bianco:

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

Riferimento:


Uso della Guava biblioteca, è molto più semplice:

return CharMatcher.WHITESPACE.matchesAnyOf(testCode);

CharMatcher.WHITESPACE è anche un sacco più approfondita quando si tratta di supporto Unicode.

Questo vi dirà se c'è qualsiasi spaziature:

Sia con loop:

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

o

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

E StringUtils.isBlank(s) vi dirà se ci sono solo whitepsaces.

utilizzare Apache Commons StringUtils :

StringUtils.containsWhitespace(str)

L'uso di questo codice, era meglio soluzione per me.

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

Si potrebbe utilizzare Regex per determinare se c'è uno spazio bianco. \s.

Più informazioni su regex qui .

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

Utilizzare org.apache.commons.lang.StringUtils.

  1. per cercare gli spazi bianchi
  

booleano withWhiteSpace = StringUtils.contains ( "il mio nome", " ");

  1. Per eliminare tutti gli spazi bianchi in una stringa
  

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

I scopo di un metodo molto semplice che utilizzano String.contains :

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

Un po 'esempio di utilizzo:

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

Output:

true
false

Si può sostanzialmente fare questo

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

È necessario scrivere booleana method.Whitespace char è 32.

È possibile utilizzare chatAt () la funzione per scoprire spazi nella stringa.

 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");
        }
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top