• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2966
  • Last Modified:

Truncating a String in C#

What is the proper syntax to truncate (reduce) a string in C#?

For example:
     myString = "SELECT * FROM table WHERE fieldname = variable AND"

and I want to cut off the last 3 characters in the string (the "AND") and make the new value be
    myString = "SELECT * FROM table WHERE fieldname = variable"

0
P1ST0LPETE
Asked:
P1ST0LPETE
  • 2
  • 2
1 Solution
 
Guy Hengel [angelIII / a3]Billing EngineerCommented:
the better way would be to build the sql string so you don't get that "AND at all...

starting with building the WHERE clause with 1=1 and the append any additional conditions with AND <condition>
     myString = "SELECT * FROM table WHERE 1=1 AND fieldname = variable "

Open in new window

0
 
P1ST0LPETEAuthor Commented:
WOW!  Good solution.  However, I'd still like to know how to truncate a string :-)
0
 
JimBrandleyCommented:
angelll is correct. However, if you have no choice in the matter,
string myString = myString.SubString(0, myString.Length - 3);

will trim the last three characters.

Jim
0
 
P1ST0LPETEAuthor Commented:
Thanks Jim.
0
 
JimBrandleyCommented:
My pleasure. Good luck.

Jim
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now