简体   繁体   中英

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"?

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);

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

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";

Alternative to @SLaks solution:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM