当我将excel数据集中的字符串复制到文本框中时,该字符串在字符串中的每个项目之间都有巨大的空格。
我目前有if (textBox1.Text.Contains(" ") == true)
来检测字符串中的空格。
我会用什么来删除这些空格?
奖金问题:我在字符串中的每个项目之间仍然需要一个空格,我如何添加它仍然删除大量空格?
private void radioGenerateScript_CheckedChanged(object sender, EventArgs e)
{
hexData.Cells.Copy();
textBox1.Clear();
textBox1.Paste();
if (textBox1.Text.Contains(" ") == true)
{
}
}
private void radioWriteScript_CheckedChanged(object sender, EventArgs e)
{
string waveForm = textBox1.Text;
System.IO.File.WriteAllText("E:/Scripts/Test.us1", waveForm);
}
答案 0 :(得分:4)
如果要删除所有类型的空格,请使用:
textBox1.Text = Regex.Replace(textBox1.Text, @"\s+", "");
\s
匹配所有空格(空格,制表符和换行符)。
答案 1 :(得分:3)
textBox1.Text = textBox1.Text.Replace(" ", "");
如果您想保留部分空格,请使用Split
和string.Join
var words = textBox1.Text.Split(new [] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
textBox1.Text = string.Join(" ", words);
答案 2 :(得分:3)
textBox1.Text = Regex.Replace(textBox1.Text, " +", " ");
您似乎将标签作为分隔符,因此以下情况更好(正如阿列克谢建议的那样):
textBox1.Text = Regex.Replace(textBox1.Text, @"\s+", " ");