user222427
user222427

Reputation:

C# how to append a string.join and not to append the very last string

Basically i'm using a string.join like below.

string Combinestr = string.Join("", newListing+"\n"+"Total Found");

however, i do not want to append the very last line in newListing. newListing is a HashSet, is this the case where I need to do a trimend after i've joined all the strings? If so, how would I do a trimend for the entire string "\nTotal Found"?

Upvotes: 1

Views: 663

Answers (4)

Jalal Said
Jalal Said

Reputation: 16162

Alternative to @SLaks solution:

int lastIndex = Combinestr.LastIndexOf("\n");

if (lastIndex > -1)
{
    Combinestr = Combinestr.Substring(0, lastIndex);
}

Upvotes: 0

musefan
musefan

Reputation: 48415

Firstly your string.Join is pointless. You are already joining the string by using the + operator. You should have it like this...

string Combinestr = string.Join("", newListing, "\n", "Total Found");

However, I would personally just do....

string Conbinestr = newListing.ToString() + "\nTotal Found";

and be done with it.

If you don't want the last item in a has set then I would loop the hash set and use a string builder...

System.Text.StringBuilder sb = new System.Text.StringBuilder();
foreach(var hash in newListing.Take(newListing.Count - 1)){
   sb.Append(hash.ToString());
}
sb.Append("\nTotal Found");

string Conbinestr = sb.ToString();

...overall thou, something doesn't seem quite right about what you are trying to do

Upvotes: 1

SLaks
SLaks

Reputation: 887453

You want that string to appear between the items in your HashSet.

That's what the first parameter is for:

string Combinestr = string.Join("\nTotal Found", newListing);

Upvotes: 8

Kon
Kon

Reputation: 27441

Actually I go in reverse and put the '\n' in front usually. In that case, you just need to make sure the first item doesn't get it appended:

if (!String.IsNullOrEmpty(newListing))
{
  newListing += "\n";
}

newListing += "Total Found";

Upvotes: 0

Related Questions