我从文本文件中分割文本,我必须比较2个字符串,一个来自文本框,另一个来自特定行的文本文件。来自文本的字符串在末尾有一个空格,并且比较总是错误的。 这是代码。谢谢!
private void button1_Click(object sender, EventArgs e)
{
Random r = new Random();
t = r.Next(1,30);
StreamReader sr = new StreamReader("NomenA1.txt");
cuv = sr.ReadToEnd().Split('\n');
string original = cuv[t];
Random num = new Random();
// Create new string from the reordered char array.
string rand = new string(original.ToCharArray().
OrderBy(s => (num.Next(2) % 2) == 0).ToArray());
textBox2.Text = rand;
button1.Visible = false;
button2.Visible = true;
}
private void button2_Click(object sender, EventArgs e)
{
button1.Visible = false;
string a =Convert.ToString(textBox1.Text.ToString());
string b = cuv[t];
if (a == b)
{
MessageBox.Show("Corect");
button1.Visible = true;
button2.Visible = false;
}
else
{
MessageBox.Show("Mai incearca"); button1.Visible = false;
}
}
答案 0 :(得分:5)
您可以使用Regex
删除所有最后一个空格:
string s = "name ";
string a = Regex.Replace(s, @"\s+$", "");
所有两个结束空间的或Trim()
函数:
string s = " name ";
string a = s.Trim();
或者如果您只想从末尾删除一个空格:
string s = "name ";
string a = Regex.Replace(s, @"\s$", "");
答案 1 :(得分:3)
如何删除字符串中的最后一个字符
var s = "Some string ";
var s2 = s.Substring(0, s.Length - 1);
或者,通常的解决方案通常是
var s3 = s.Trim(); // Remove all whitespace at the start or end
var s4 = s.TrimEnd(); // Remove all whitespace at the end
var s5 = s.TrimEnd(' '); // Remove all spaces from the end
或非常具体的解决方案
// Remove the last character if it is a space
var s6 = s[s.Length - 1] == ' ' ? s.Substring(0, s.Length - 1) : s;
答案 2 :(得分:0)
你试过吗.Trim()
String myStringA="abcde ";
String myStringB="abcde";
if (myStringA.Trim()==myStringB)
{
Console.WriteLine("Matches");
}
else
{
Console.WriteLine("Does not match");
}
答案 3 :(得分:-2)
怎么样:
string s = "name ";
string a = s.Replace(" ", "");
这对我来说似乎很简单,对吧?