Java method to remove the last redundant comma when concatenating strings

  • 2020-04-01 03:43:49
  • OfStack

This article illustrates how to remove the last redundant comma when concatenating strings in Java. Share with you for your reference. Specific analysis is as follows:

Here's the code:


for (int t = 0; t < memberLen; t++) {
 memTemp = stafferMap.get(strMember[t]);
 if(memTemp != null){
 memberNames += memTemp + ",";
 }
}

For the above code, the concatenated string will have an extra ",", such as: "str1,str2,str3,", to remove the comma after str3, you can use the following method:


memberNames = memberNames.substring(0,memberNames.length()-1);

For example, when Team1=test ', 'u1-team ',' v-team ', '

How to change:

Team1= 'test ', 'u1-team ',' v-team '

Available:


Team1 = " ' " + Team1.Substring(0, Team1.Length - 2);

Here's what others have to add:

The following code can be used if splicing


StringBuilder sdb = new StringBuilder();
for ( int t = 0; t < memberLen; t++ )
{
	memTemp = stafferMap.get( strMember[t] );
	if ( memTemp != null )
	{
		if ( sbd.length > 0 )
		{
			sbd.append( "," ).append( memTemp );
		}else{
			sbd.append( memTemp );
		}
	}
}
System.out.prentln( " No extra commas: " + sbd.toString() );

I hope this article has been helpful to your Java programming.


Related articles: