Link to home
Start Free TrialLog in
Avatar of amaximia
amaximiaFlag for United States of America

asked on

Delete spaces after end of string containing two words VB.NET 2005

I would like to take a string and if it has two words in it, I would like to strip any spaces that occur at the end of the string (something like a "trim right").  However, if it is only one word, then I would like to leave a single space after the word, if the user entered it, and get rid of anything else which occurs after.  For example:

"Hello, world   " gets converted to "Hello, world"

"Hello    " gets converted to "Hello "

How do I do this in VB.NET 2005?

Thanks.
Avatar of gregoryyoung
gregoryyoung
Flag of Canada image

You can check the no of spaces in a string using string function(IndexOf(' ')) and space count is grater than 2 use Trim function, otherwise add a space at the end.
Avatar of amaximia

ASKER

Is there any way to say if I can find in the string "[a-Z]<space>[a-Z]" then do a TrimEnd, else leave it alone?
Well you could check the string with a regexp then use an if() to check for matching the conditionally run the TrimEnd()
SOLUTION
Avatar of Jorge Paulino
Jorge Paulino
Flag of Portugal image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
except that would also validate 1234 5678 and "  "as applying :)

Yes gregoryyoung but if you are looking for word and not number you can do that.
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Sabeesh,

I will, after converting to VB which should not be a problem.  Will it work under these circunstances:

"hello world" is unchanged
"hello world " (one space after) becomes "hello world" (no spaces after)
"hello " (one space after) is unchanged because it is only one word
"hello      " (several spaces after) becomes "hello " (one space after)

Thanks.
string str = "hello      ";
        Regex r = new Regex(@"\s{1,}");
        Match m = r.Match(str.TrimEnd());
       if(m.Success )
       {
           str = str.TrimEnd();
       }

You can try this also. so this will remove space from the end and later you can add the space at the end if it is required.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of sakshi_net
sakshi_net

inside if condition I am checking if the entered string contains only one word then the final string will have one space added at the end