Search code examples
arraysrustwhitespacetrim

Trimming whitespace in Array


I have been trying to trim whitespaces in my long array which consists of almost all the periodic table elements but not able to find the function that does that, I did read the documentation on trim but found out that none of them work with the array.

Here is my long array

let mut elements = ["Please start with 1"," Hydrogen"," Helium","Lithium"," Beryllium","Boron","Carbon"," Nitrogen","Oxygen","Fluorine","Neon","Sodium","Magnesium","Aluminium","Silicon","Phosphorus","Sulfur"," Chlorine","Argon","Potassium","Calcium "," Scandium","Titanium","Vanadium",
                "Chromium","Manganese"," Iron","Cobalt","Nickel","Copper","Zinc","Gallium","Germanium","Arsenic"," Selenium","Bromine","Krypton","Rubidium","Strontium","  Yttrium","Zirconium ","Niobium ","Molybdenum ","Technetium ","Ruthenium ","Rhodium","Palladium","Silver",
                "Cadmium "," Indium ","Tin","Antimony"," Tellurium","Iodine","Xenon","Cesium","Barium","Lanthanum","Cerium"," Praseodymium","Neodymium"," Promethium "," Samarium ","Europium "," Gadolinium","Terbium "," Dysprosium ","Holmium "," Erbium","Thulium","Ytterbium","Lutetium","Hafnium",
                "Tantalum "," Tungsten","Rhenium ","Osmium ","Iridium ","Platinum","Gold","Mercury"," Thallium","Lead ","Bismuth"," Polonium" ,"Astatine","Radon ","Francium ","Radium"," Actinium","Thorium"," Protactinium","Uranium","Neptunium","Plutonium","Americium","Curium","Berkelium","Californium"];

Now in a few elements there are whitespaces that ruin the output.

Is there any way you can trim the whitespaces in an array?


Solution

  • Just use map with trim as:

    let trimmed = elements.map(str::trim);
    

    Playground

    Notice that this builds a new array.