0

I have a tons of strings and values like "test la'la'la'la'la".

I need to find all ' indexes and insert another ' to string. => "test la''la''la''la''la"

Because of PostgreSQL.

How to do it more effectionaly? I have a list of thousands strings like this, so i need make it as faster as possible.

Maybe need use LINQ?

  • Do you need the indexes only to insert the other ' or do you want to use these indexes in your program? – SomeBody Mar 18 '20 at 08:51
  • 2
    Does `string.Replace("'", "''")` help you? – mu88 Mar 18 '20 at 08:54
  • 5
    _"I need to find all ' indexes and insert another ' to string. => "test la''la''la''la''la""_ - Doesn't PostgreSQL support prepared statements? [It looks like it does](http://zetcode.com/csharp/postgresql/). Prepared statements are the correct way to do this. So you don't write `INSERT INTO table (a) VALUES ('my '' dangerous string');`, you write `INSERT INTO table (a) VALUES (@safeParameter)` and pass your string as a parameter. – ProgrammingLlama Mar 18 '20 at 08:54
  • 3
    1. You shouldn't care about having a `'` in your string, instead, use parameterized queries. That is the correct way to send data to the database. Any modern database supports parameters. 2. the .Net `string` class has a `Replace` method that does exactly that - replace each occurrence of a substring with a different substring. – Zohar Peled Mar 18 '20 at 08:57
  • Does this answer your question? [What are good ways to prevent SQL injection?](https://stackoverflow.com/questions/14376473/what-are-good-ways-to-prevent-sql-injection) – xdtTransform Mar 18 '20 at 08:59
  • And [How can I add user-supplied input to an SQL statement?](https://stackoverflow.com/questions/35163361/how-can-i-add-user-supplied-input-to-an-sql-statement). this one look better. – xdtTransform Mar 18 '20 at 09:00

1 Answers1

2

How about a simple Select() and Replace();

[Test]
public void Replace_in_strings_works()
{
    var strings = new List<string>
    {
        "one'two'three'",
        "four'five'six'",
    };
    var transformedStrings = strings.Select(x => x.Replace("'", "''")).ToList();
    transformedStrings.ForEach(Console.WriteLine);
}
DaggeJ
  • 2,094
  • 1
  • 10
  • 22
  • `Select` has nothing to do with that. `Replace` is all that's needed to get what the OP have asked for - however, it seems like the OP is asking for the wrong reasons - which is why John, xdtTrasnsform and myself have commented on the question as we did. – Zohar Peled Mar 18 '20 at 09:04