Reputation: 21
I split text from a text file and I have to compare 2 strings, one from a textbox and the other one from a text file from a specific line. That string from text has a space at the end and the comparison is always wrong. Here is the code. Thank you!
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;
}
}
Upvotes: 0
Views: 4058
Reputation: 7352
You can use Regex
to remove all last space:
string s = "name ";
string a = Regex.Replace(s, @"\s+$", "");
or Trim()
function for all both end space:
string s = " name ";
string a = s.Trim();
or if you want to remove only one space from the end:
string s = "name ";
string a = Regex.Replace(s, @"\s$", "");
Upvotes: 5
Reputation:
Have you tried .Trim()
String myStringA="abcde ";
String myStringB="abcde";
if (myStringA.Trim()==myStringB)
{
Console.WriteLine("Matches");
}
else
{
Console.WriteLine("Does not match");
}
Upvotes: 0
Reputation: 19203
How could I remove the last character in a string
var s = "Some string ";
var s2 = s.Substring(0, s.Length - 1);
Alternatively a general solution is usually
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
Or a very specific solution
// Remove the last character if it is a space
var s6 = s[s.Length - 1] == ' ' ? s.Substring(0, s.Length - 1) : s;
Upvotes: 3
Reputation: 169
What about :
string s = "name ";
string a = s.Replace(" ", "");
That seems pretty simple to me, right?
Upvotes: -1