Solved

C# Remove a certain number of characters from the end of a string.

Posted on 2009-06-28
7
759 Views
Last Modified: 2012-05-07
I have been wondering if there was an easy way to just delete the last certain number of characters from a string.

Like, I want to just remove the last 4 or 5 characters from a string.

I have found some round a bout ways to do it, but didn't know if there was a simple way to do it I am just neglecting to find?
0
Comment
Question by:dcolanduno
7 Comments
 
LVL 40

Accepted Solution

by:
mrjoltcola earned 50 total points
ID: 24732924
Try this for arbitrary chars. This takes 1 char off of the string.

String s = "12345";
s = s.Substring(0, s.Length - 1);
0
 
LVL 40

Expert Comment

by:mrjoltcola
ID: 24732936
Also, a shorthand for Substring that can also come in handy is:

s = s.Remove(3);

Removes everything from the startIndex and on, so the above would leave you with only the first 3 characters
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 24733116
You could write an Extension method:
http://msdn.microsoft.com/en-us/library/ms364047(VS.80).aspx#cs3spec_topic3
http://msdn.microsoft.com/en-us/library/bb383977.aspx

Usage:

            string str = "abcde";
            str = str.TrimRight(2);
            MessageBox.Show(str);

Code:
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;
 

namespace WindowsFormsApplication1

{

    public static class MyExtensions

    {

        public static String TrimRight(this String str, int NumCharsToTrim)

        {

            return NumCharsToTrim <= str.Length ? str.Substring(0, str.Length - NumCharsToTrim) : "";

        }

    }

}

Open in new window

0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 22

Expert Comment

by:cookre
ID: 24733119
I'm a paranoid type - I'd extend mrjoltcola's way thusly:

if (s.Lenth >= NumCharsToChop)  
      s=s.Substring(0,s.Length-NumCharsToChop);
else oops...
0
 
LVL 8

Expert Comment

by:InternalStatic
ID: 24733292
Unfortunately, there is no good way to truly remove the last few characters from a String; they are "immutable", meaning that, once created, they may not be changed. In order to "Edit" a string, you always have to have a round-about way of doing so; you have to create a new String with the desired information. Substring does just that, so take your string (let's assume the String you want to "remove" characters from is declared as "String s;"), and assign it to itself using Substring:
s = s.Substring(0, s.Length - numCharsToRemove);
The first argument (0) just means that the Substring should start including characters at position 0. The next argument is how many charactesr to include, so by taking the String's length minus however many characters you want to "remove", we effectively cut off the last few characters of the String.
I realize the question was basically already answered (though not officially), but I figured you may benefit from a more detailed explanation.
Hope it helps,
Nate
0
 

Author Closing Comment

by:dcolanduno
ID: 31597750
Thank you, worked perfectly for what I was attempting to do. Wish there was a way to correct my point slip up! :|
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Image(7) 1 53
How to Get total minutes between two hours 4 44
Achieve json result 2 64
C# parent child form 5 13
Introduction                                                 Was the var keyword really only brought out to shorten your syntax? Or have the VB language guys got their way in C#? What type of variable is it? All will be revealed.   Also called…
Introduction Although it is an old technology, serial ports are still being used by many hardware manufacturers. If you develop applications in C#, Microsoft .NET framework has SerialPort class to communicate with the serial ports.  I needed to…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.
A company’s greatest vulnerability is their email. CEO fraud, ransomware and spear phishing attacks are the no1 threat to a company’s security. Cybercrime is responsible for the largest loss of money to companies today with losses projected to r…

929 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now