繁体   English   中英

如何从c#中的字符串中删除最后一个空格字符?

[英]How could I remove the last space character from a string in c#?

我从一个文本文件中拆分文本,我必须比较两个字符串,一个字符串来自文本框,另一个字符串来自特定行中的文本文件。 文本中的字符串结尾处有空格,并且比较总是错误的。 这是代码。 谢谢!

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;
    }
}

您可以使用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$", "");

如何删除字符串中的最后一个字符

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;

你尝试过.Trim()

String myStringA="abcde "; 
String myStringB="abcde"; 

if (myStringA.Trim()==myStringB) 
{
  Console.WriteLine("Matches"); 
} 
else 
{
  Console.WriteLine("Does not match");    
}

关于什么 :

string s = "name ";
string a = s.Replace(" ", "");

对我来说这很简单,对吧?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM