ComeçarComece de graça

Cleaning strings

You've extracted product names from your electronics inventory into a list of strings. The product names are messy, and some have leading and trailing spaces, non-letters, multiple spaces, or mixed cases. Clean the product names from your inventory.

Este exercício faz parte do curso

Cleaning Data in Java

Ver curso

Instruções do exercício

  • Remove leading and trailing spaces from each product name.
  • Replace multiple spaces with a single space in the products.
  • Convert all product names to lowercase.

Exercício interativo prático

Experimente este exercício completando este código de exemplo.

import java.util.Arrays;
import java.util.List;

public class ProductDataExample {
	public static void main(String[] args) {
    	String[] messyProducts = {
            "Laptop ", "SMARTPHONE", 
            "Monitor *(Display)*", "   Bluetooth    Speaker   "
        };

        Arrays.stream(messyProducts)
              // Remove leading and trailing spaces
              .map(s -> s.____()
                     .replaceAll("[^a-zA-Z\\s]", "")
                     // Replace multiple spaces with a single space
                     .replaceAll("____", " ")
                     // Convert to lowercase
                     .____())
              .forEach(System.out::println);
    }
}
Editar e executar o código