31

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

Darqer
  • 2,847
  • 9
  • 45
  • 65
  • 1
    Could you clarify your question a little bit! – Mazen Elkashef Apr 21 '11 at 15:09
  • from string abc I want to make string "abc" and I wonder whether there is some build in method in some class that can do the job. I know it is 5 line of code to write your own. – Darqer Apr 21 '11 at 15:12
  • @Darger: And what if the string contains a quote? What will you use it for? – H H Apr 21 '11 at 19:52

9 Answers9

39

Do you mean just adding quotes? Like this?

text = "\"" + text + "\"";

? I don't know of a built-in method to do that, but it would be easy to write one if you wanted to:

public static string SurroundWithDoubleQuotes(this string text)
{
    return SurroundWith(text, "\"");
}

public static string SurroundWith(this string text, string ends)
{
    return ends + text + ends;
}

That way it's a little more general:

text = text.SurroundWithDoubleQuotes();

or

text = text.SurroundWith("'"); // For single quotes

I can't say I've needed to do this often enough to make it worth having a method though...

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • you're slipping. `this text` should be `this string text` :) – Jamiec Apr 21 '11 at 15:14
  • 3
    Easy to write, but you have to write it a billion times unless you make your own library or something. Or bring in a third party lib for something this trivial. Would be awfully handy if it was just in the standard lib. – jpmc26 Sep 06 '17 at 23:41
  • @jpmc26: I can't say I have to do it very often... Partly as if I'm quoting, it's usually to write JSON or something similar, in which case I'd be using a library anyway. – Jon Skeet Sep 07 '17 at 05:05
  • I find I use it fairly frequently when building up logging messages, especially with a list of things. (E.g., `String.Join(", ", someValues.Select(v => "\"" + v + "\"")` and then passing *that* into a `Format` call.) It comes up in PowerShell, too, when trying to pass things to an executable a certain way. (SQL*Plus is quite finicky about when the quote marks go.) – jpmc26 Sep 07 '17 at 05:10
  • 1
    @jpmc26: Well in C# I'd use interpolated string literals making it much simpler - and I'd probably use single quotes to avoid having to escape anything. But if you do decide to write a helper method, it would only be once per application. Either way it doesn't feel like a big deal to me. For SQL I wouldn't be building value into the SQL at all, but using parameterized SQL wherever possible. – Jon Skeet Sep 07 '17 at 06:05
  • SQL*Plus is Oracle's command line tool, so I'm talking about command lines, not SQL statements. ;) – jpmc26 Sep 07 '17 at 13:47
  • @jpmc26: Right, but my point is that that's an edge case, not something you do "a billion times". You may well want to write a library to make it easier to start processes, and that would have more than just quoting in. – Jon Skeet Sep 07 '17 at 13:48
12
string quotedString = string.Format("\"{0}\"", originalString);
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
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())
Jamiec
  • 133,658
  • 13
  • 134
  • 193
5

No but you can write your own or create an extension method

string AddQuotes(string str)
{
    return string.Format("\"{0}\"", str);
}
Bala R
  • 107,317
  • 23
  • 199
  • 210
3

Using Escape Characters

Just prefix the special character with a backslash, which is known as an escape character.

Simple Examples

string MyString = "Hello";
Response.Write(MyString);

This would print:

Hello

But:

string MyString = "The man said \"Hello\"";
Response.Write(MyString);

Would print:

The man said "Hello"

Alternative

You can use the useful @ operator to help escape strings, see this link:

http://www.kowitz.net/archive/2007/03/06/the-c-string-literal

Then, for quotes, you would use double quotes to represent a single quote. For example:

string MyString = @"The man said ""Hello"" and went on his way";
Response.Write(MyString);

Outputs:

The man said "Hello" and went on his way
Tom Gullen
  • 61,249
  • 84
  • 283
  • 456
2

In my case I wanted to add quotes only if the string was not already surrounded in quotes, so I did:

(this is slightly different to what I actually did, so it's untested)

public static string SurroundWith(this string text, string ends)
{
    if (!(text.StartsWith(ends) && text.EndsWith(ends)))
    {
        return string.Format("{1}{0}{1}", text, ends);
    }
    else
    {
        return text;
    } 
}
soupy1976
  • 2,787
  • 2
  • 26
  • 34
2

I'm a bit C# of a novice myself, so have at me, but I have this in a catch-all utility class 'cause I miss Perl:

// overloaded quote - if no quote chars spec'd, use ""
public static string quote(string s) {
    return quote(s, "\"\"");
}

// quote a string
// q = two quote chars, like "", '', [], (), {} ...
//     or another quoted string (quote-me-like-that)
public static string quote(string s, string q) {

    if(q.Length == 0)        // no quote chars, use ""
        q = "\"\"";
    else if(q.Length == 1)    // one quote char, double it - your mileage may vary
        q = q + q;
    else if(q.Length > 2)    // longer string == quote-me-like-that
        q = q.Substring(0, 1) + q.Substring(q.Length - 1, 1);

    if(s.Length == 0)    // nothing to quote, return empty quotes
        return q;

    return q[0] + s + q[1];

}

Use it like this:

quote("this with default");
quote("not recommended to use one char", "/");
quote("in square brackets", "[]");
quote("quote me like that", "{like this?}");

Returns:

"this with default"
/not recommended to use one char/
[in square brackets]
{quote me like that}
Rob Craig
  • 121
  • 2
  • 4
2

Modern C# version below. Using string.Create() we avoid unnecessary allocations:

public static class StringExtensions
{
    public static string Quote(this string s) => Surround(s, '"');

    public static string Surround(this string s, char c)
    {
        return string.Create(s.Length + 2, s, (chars, state) =>
        {
            chars[0] = c;
            state.CopyTo(chars.Slice(1));
            chars[^1] = c;
        });
    }
}
l33t
  • 18,692
  • 16
  • 103
  • 180
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));
}
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
sobby01
  • 1,916
  • 1
  • 13
  • 22