19

How to check the last char of a string and see its a blank space? If its a blank space remove it?

Leniel Maccaferri
  • 100,159
  • 46
  • 371
  • 480

7 Answers7

60

Specific for one space character:

if(MyString.EndsWith(" "))
    MyString = MyString.Substring(0, MyString.Length - 1);

or for any whitespace

MyString = MyString.TrimEnd();
Michiel van Vaardegem
  • 2,260
  • 20
  • 35
4

Use the Trim method of string class

Jahan Zinedine
  • 14,616
  • 5
  • 46
  • 70
3
string Original= "I am on Test ";

string Temp = Original.Substring( Original.Length - 1 );
Original = Original.Remove( Temp.Trim().Length > 0 ? 0 : Original.Length - 1);
Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
Ashfaq Shaikh
  • 1,648
  • 12
  • 20
2

Use special designed for it functions Trim, TrimStart, TrimEnd:

var trimmedString = "this is my string with space at the end ".TrimEnd();
Samich
  • 29,157
  • 6
  • 68
  • 77
2
string someString = "i will have some blank space at the end    ";
someString = someString.Trim(); //blank space now removed

It's worth noting that this will also remove blank spaces at the start of a string also

WickyNilliams
  • 5,218
  • 2
  • 31
  • 43
0

You can use a Trim function with a char array as parameter to remove empty spaces and any other unwanted chars:

var formattedString = "formatted, but with empty values, , .";
var trimmedString = formattedString.TrimEnd(new char[] { ' ', ',', '.'});
// result = "formatted, but with empty values"
Skittles86
  • 96
  • 1
  • 4
0

another code for check the last char of a string is a blank char:

string text = "hello  ";
bool isBlank = text[text.Length -1].ToString().Trim().Length > 0 ? false : true;
Taher Fattahi
  • 951
  • 1
  • 6
  • 14