Question

Which is the correct way of doing of below?

Is it first or second or both of them are correct?

string strName=" Avinash ";
strName=strName.Trim();

(or)

string strName="Avinash";
string strTrimmedname=string.empty;
strTrimmedname=strName.Trim();

Updated:

NO need of original value , i need only trimmed string. I was just confused because it is not correct in java..

Was it helpful?

Solution

In the first approach you're removing the spaces before and behind the string, then you're reassinging the new string to the same variable.

In the second approach you're creating a new variable for the new string.

There is no "best" way, if you need to retain the old string you need to use two variables.

However, this line is redundant:

string strTrimmedname = string.empty;

You could give it the correct value in the first place:

string strTrimmedname = strName.Trim();

Updated question

NO need of original value , i need only trimmed string.

Then it's a matter of taste which way should be preferred. Use whatever you find more readable. The first is not introducing a new variable which can help to prevent careless mistakes. The second might be more readable because of the more meaningful variable name.

So if possible i would use option 3: string strTrimmedname =" Avinash ".Trim();

OTHER TIPS

If you want to keep the original value of strName then the second approach is preferred, although you don't need to initialize it with String.Empty you can just assign it directly

string strName = " Avinash ";
string strTrimmedname = strName.Trim();

If your intention is simply to remove the whitespace from strName then the first option is fine. Or alternatively, there is an option number 3

string strName = " Avinash ".Trim();

I've would have done as the first alternative. But then, it depends on if you need two variables or not.

The both Approaches are correct when you need string to be set in Same string then first Approach is correct.

When you need to store the value of variable in another another variable then Second Approach is correct.

but use the first approach because there is no need of Additional variable(Reduce memory by not using additional variables).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top