Alex Rivera | Logout

Auto quotes around string in c# - build in method?

Asked 2011-04-21T15:07:37.317
31

Is there some build in method that add quotes around string in c# ?

Edit
Report

3 Answers

13
string quotedString = string.Format("\"{0}\"", originalString);
answered 2011-04-21T15:11:44.247
11

Yes, using concatenation and escaped characters

myString = "\"" + myString + "\"";

Maybe an extension method

public static string Quoted(this string str)
{
    return "\"" + str + "\"";
}

Usage:

var s = "Hello World"
Console.WriteLine(s.Quoted())
answered 2011-04-21T15:10:16.137
1

There is no such built in method to do your requirement

There is SplitQuotes method that does something Input - This is a "very long" string Output - This, is, a, very long, string

When you get a string from textbox or some control it comes with quotes.

If still you want to place quotes then you can use this kind of method

private string PlaceQuotes(string str, int startPosition, int lastPosition)
{
    string quotedString = string.Empty;
    string replacedString = str.Replace(str.Substring(0, startPosition),str.Substring(0, startPosition).Insert(startPosition, "'")).Substring(0, lastPosition).Insert(lastPosition, "'");
    return String.Concat(replacedString, str.Remove(0, replacedString.Length));
}
answered 2011-04-21T15:56:45.850

Your Answer