How to check the last char of a string and see its a blank space
Asked Answered
S

7

20

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

Sectary answered 9/12, 2011 at 10:31 Comment(1)
Do you only want to remove the last char if blank, or all trailing whitespace?Semaphore
S
60

Specific for one space character:

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

or for any whitespace

MyString = MyString.TrimEnd();
Siward answered 9/12, 2011 at 10:33 Comment(1)
Note typo: should be .Substring, not SubString.Oberammergau
T
4

Use the Trim method of string class

Thedrick answered 9/12, 2011 at 10:34 Comment(0)
N
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);
Nydianye answered 9/12, 2011 at 13:4 Comment(0)
A
2

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

var trimmedString = "this is my string with space at the end ".TrimEnd();
Annulate answered 9/12, 2011 at 10:33 Comment(2)
Just to be clear, this will remove ALL whitespace from the front and the end of the string, not just a single space from the end.Briefs
Updated to TrimEnd function :). Thanks.Annulate
E
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

Earlearla answered 9/12, 2011 at 10:34 Comment(0)
T
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"
Thorazine answered 8/4, 2019 at 11:24 Comment(0)
T
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;
Tetany answered 14/4, 2020 at 5:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.