Shah Abdullah
Shah Abdullah

Reputation: 405

Not Trimming white spaces from a string in c#

Trim() Function Not Working Please Help its not trimming the white space.

string samplestring = "172-6573-4955";  
string[] array = samplestring .Split('-');
string firstElem = array.First();
string restOfArray = string.Join(" ", array.Skip(1));
array[1] = restOfArray.Trim(); // providing value "6573 4955" 

The scenario is I am splitting string and merging 2nd and last index into one but it's merging with white spaces.

Upvotes: 1

Views: 233

Answers (6)

Prashant19sep
Prashant19sep

Reputation: 183

Try this:

string samplestring = "172-6573-4955";
string[] array = samplestring.Split(new char[] {'-'},2);
string result = array[1].Replace("-","");

Also, for your question about randomly putting spaces, can u pls explain "randomly" here.

Upvotes: 0

l'L'l
l'L'l

Reputation: 47169

Trim really isn't need here; you can simply split the string and join the parts you want:

string source = "172-6573-4955";  
string[] splitter = new string[] {"-"};
string[] result;
result = source.Split(splitter, StringSplitOptions.None);
string final = (result[1] + result[2]);
Console.Write(final);

Result:

65734955

Upvotes: 0

pid
pid

Reputation: 11597

To just split the first n-let from the rest use an additional array or you will end up with spurious data. And join with the correct separator you used in split(-):

string restOfArray = string.Join("-", array.Skip(1));
string[] result = new string[] { firstElem, restOfArray };

You don't need Trim().

You can simplify your code this way:

string[] splitCode(string code)
{
    string[] segments;

    segments = code.Split('-');

    return new string[] { segments.First(), string.Join("-", segments.Skip(1)) };
}

Upvotes: 0

nsgocev
nsgocev

Reputation: 4470

Trim is working as expected. Taken from String.Trim Method:

Removes all leading and trailing white-space characters from the current String object.

The possible solutions for you are :

string restOfArray = string.Join(string.Empty, array.Skip(1)); 

Or

 array[1] = restOfArray.Replace(" ", string.Empty).Trim();

Upvotes: 0

toadflakz
toadflakz

Reputation: 7944

Trim() removes whitespace from the front and back of a string, not in the middle. The whitespaces in the middle are being inserted by the " " provided as the parameter to Join() method. You could provide string.empty instead.

Upvotes: 3

Rahul Tripathi
Rahul Tripathi

Reputation: 172428

Trim is used to remove all leading and trailing white-space. And you want to trim the white space from middle. You may try like this:

string restOfArray = string.Join("", array.Skip(1)); 

or better:

string restOfArray = string.Join(string.Empty, array.Skip(1)); 

instead of

string restOfArray = string.Join(" ", array.Skip(1)); 

Upvotes: 2

Related Questions