"Peter Duniho" <(E-Mail Removed)> wrote in message
news:(E-Mail Removed)...
> On 1/27/11 12:03 PM, mp wrote:
>> to ensure string is legal field name, first thought is below:
>>
>> private string ConvertToDBFieldName ( string str )
>> {//disallowed characters in database fieldname ` . ! ? [ ] " *
>> ?
>> StringBuilder sb = new StringBuilder ( str );
>> sb.Replace ( " ", "_" );
>> sb.Replace ( "`", "" );
>> sb.Replace ( ".", "" );
>> sb.Replace ( "!", "" );
>> sb.Replace ( "?", "" );
>> sb.Replace ( "[", "" );
>> sb.Replace ( "]", "" );
>> sb.Replace ( "\"", "" );
>> sb.Replace ( "*", "" );
>> sb.Replace ( "?", "" );
>> return sb.ToString ( );
>> }
>> comments?
>
> Another example of where the Regex class might be nicer. But even without
> Regex, it can be somewhat simpler/more-readable:
>
> private static HashSet<char> _removeChars =
> new HashSet(new char[] { '`', '.', '!', '?', '[', ']', '\\', '*',
> '?' });
>
> private string ConvertToDBFieldName(string str)
> {
> StringBuilder sb = new StringBuilder(str.Length);
>
> foreach (char ch in str)
> {
> if (ch == ' ')
> {
> sb.Append('_');
> }
> else if (!_removeChars.Contains(ch))
> {
> sb.Append(ch);
> }
> }
>
> return str;
> }
>
> The use of repeated calls to Replace() is not quite as bad when using
> StringBuilder as if you were using String. But it's still potentially
> expensive, and in any case always excessively so. IMHO, simply filtering
> as you copy characters is clearer and more efficient. What's not to like?
> 
>
> Pete
very nice!
:-)
thanks
mark
ps I assumed you meant > return sb.ToString();
and it seemed to want HashSet<char>(new char[]
i'll have to give some thought to the regex version..
still not in my head yet.
:-)
i'm sure there's a simple negating character grouping construct...
i'll look it up
thanks again
mark