簡體   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