2010-05-06 96 views
1

我有一组字符串,其中包含一个或多个由逗号,逗号加上一个或多个空格或潜在地两者分隔的问号。因此,这些字符串都是可能的:字符串操作函数的帮助

BOB AND ? 
BOB AND ?,?,?,?,? 
BOB AND ?, ?, ? ,? 
BOB AND ?,? , ?,? 
?, ?    ,? AND BOB 

我需要@P#更换问号,使上述样品将成为:

BOB AND @P1 
BOB AND @P1,@P2,@P3,@P4,@P5 
BOB AND @P1,@P2,@P3,@P4 
BOB AND @P1,@P2,@P3,@P4 
@P1,@P2,@P3 AND BOB 

什么是这样做没有正则表达式或LINQ的最佳方式?

回答

1

我忽略的空间微调您的输出的例子,因为如果这是在SQL语句中使用的空间是无关紧要。这应该对使用的StringBuilder执行得很好,由于不是重复调用ReplaceSubstring或其他字符串方法:

public static string GetParameterizedString(string s) 
{ 
    var sb = new StringBuilder(); 
    var sArray = s.Split('?'); 
    for (var i = 0; i < sArray.Length - 1; i++) 
    { 
     sb.Append(sArray[i]); 
     sb.Append("@P"); 
     sb.Append(i + 1); 
    } 
    sb.Append(sArray[sArray.Length - 1]); 
    return sb.ToString(); 
} 
+1

空格只影响我的强迫症,但仁慈地我不必看这些查询。 :) – MusiGenesis 2010-05-06 01:49:28

+0

大声笑,希望我的例子很整洁。 – RedFilter 2010-05-06 01:53:09

+0

在SQL Server中(这不是)像这样的查询中的空格可能会影响执行计划缓存。两个只能用空格区分的查询不会受益于对方的缓存计划(无论如何我都很确定)。 – MusiGenesis 2010-05-06 01:53:19

1

如果你不想要正则表达式或LINQ,我只需要编写一个循环,并使用这个问题中的“ReplaceFirst”方法遍历字符串,替换每个出现的?用适当的@P#\

How do I replace the *first instance* of a string in .NET?

也许是这样的:

int i = 0; 
while (myString.Contains("?")) 
{ 
    myString = myString.ReplaceFirst("?", "@P" + i); 
    i++; 
} 

注意, “ReplaceFirst” 不上线的标准方法 - 你要实现它(例如作为。在这个例子中是扩展方法)。

+0

LOL。在我阅读剩下的答案之前,我正在踢自己错过了String的'ReplaceFirst'方法。 Jeez,你想要没有做任何实际工作的支票? :) – MusiGenesis 2010-05-06 01:35:24

1

为什么不生成你的SQL,因为你的参数在你的代码中定义了正确的CASE并且在它准备好时在最后执行呢?

+0

SQL已经为允许参数问号的数据库生成,我们现在必须将它用于没有参数的数据库。 – MusiGenesis 2010-05-06 01:45:36

0

我觉得像下面的东西应该这样做。

string input = "BOB AND ?,?,?,?,?"; 
int number = 1; 
int index = input.IndexOf("?"); 
while (index > -1) 
{ 
    input = input.Substring(0, index).Trim() + " @P" + number++.ToString() + input.Substring(index + 1).Trim(); 
    index = input.IndexOf("?"); 
} 
1

如果你想要的东西开箱:)

string toFormat = "?, ?    ,? AND BOB"; 
while (toFormat.Contains(" ")) 
    toFormat = toFormat.Replace(" ", " "); 
toFormat = toFormat.Replace("?", "{0}"); 
string formated = string.Format(toFormat, new PCounter()); 

的在哪里PCounter是这样的

class PCounter{ 
    int i = 0; 
    public override string ToString(){ 
     return "@P" + (++i); 
    } 
} 
+0

这很酷。我没有意识到一个arg的ToString方法被每个占位符重新调用。 – MusiGenesis 2010-05-06 02:12:02