修剪数组中的空格
Trimming whitespace in Array
我一直在尝试 trim 我的长数组中的空格,它由几乎所有周期性 table 元素组成,但找不到执行此操作的函数,我确实阅读了文档trim 但发现其中 none 个与数组一起工作。
这是我的长数组
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"];
现在在一些元素中有空格会破坏输出。
有什么方法可以 trim 数组中的空格?
只需使用 map
和 trim
作为:
let trimmed = elements.map(str::trim);
请注意,这将构建一个新数组。
您可以在不构建新数组的情况下通过修改每个元素来完成此操作。
for word in elements.iter_mut() {
*word = word.trim();
}
或者使用迭代器
elements.iter_mut().for_each(|word| *word = word.trim());
我一直在尝试 trim 我的长数组中的空格,它由几乎所有周期性 table 元素组成,但找不到执行此操作的函数,我确实阅读了文档trim 但发现其中 none 个与数组一起工作。
这是我的长数组
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"];
现在在一些元素中有空格会破坏输出。
有什么方法可以 trim 数组中的空格?
只需使用 map
和 trim
作为:
let trimmed = elements.map(str::trim);
请注意,这将构建一个新数组。
您可以在不构建新数组的情况下通过修改每个元素来完成此操作。
for word in elements.iter_mut() {
*word = word.trim();
}
或者使用迭代器
elements.iter_mut().for_each(|word| *word = word.trim());