Replace Multiple Characters in string - c#

Hi all a have a program working but return string like ")Hi("
it should be "(Hi)" so i need to replace '(' with ')' and replace
')' with '('
it sounds easy
s.Replace('(',')').Replace(')','(')
the trick is that after the first replace the string change from
")Hi(" to "(Hi(" after the second the replace will change both characters back
the final will become ")Hi)"
Help Please

You could also use a regex replacement.
s = System.Text.RegularExpressions.Regex.Replace(s, #"[)](\w+)[(]", "($1)");

You cannot use Replace because it works its replacement operation on the whole string, not char by char.
A simple brute force solution could be this one
void Main()
{
// A dictionary where every key points to its replacement char
Dictionary<char, char> replacements = new Dictionary<char, char>()
{
{'(', ')'},
{')', '('},
};
string source = ")Hi(";
StringBuilder sb = new StringBuilder();
foreach (char c in source)
{
char replacement = c;
if(replacements.ContainsKey(c))
replacement = replacements[c];
sb.Append(replacement,1);
}
Console.WriteLine(sb.ToString());
}
You can transform this in an extension method adding to a static class
public static class StringExtensions
{
public static string ProgressiveReplace(this string source, Dictionary<char, char> replacements)
{
StringBuilder sb = new StringBuilder();
foreach (char c in source)
{
char replacement = c;
if (replacements.ContainsKey(c))
replacement = replacements[c];
sb.Append(replacement, 1);
}
return sb.ToString();
}
}
and call it from your code with
Dictionary<char, char> replacements = new Dictionary<char, char>()
{{'(', ')'},{')', '('}};
s = s.ProgressiveReplace(replacements);

var s = ")Hi(";
var sb = new StringBuilder();
foreach (var c in s)
if (c == ')')
sb.Append('(');
else if (c == '(')
sb.Append(')');
else
sb.Append(c);
s = sb.ToString();

Method 1)
Use the following:
var requiredString = string.Join(string.Empty, str.Select(x=>{if (x == '(') x = ')'; else if (x == ')') x = '('; return x;}));
Method 2)
Or you can Use following Extension Method:
public static class StringExtensions
{
public static string ReplaceMultiple(this string source, Dictionary<char, char> replacements)
{
return string.Join(string.Empty , source.Select(x=>Replace(x,replacements)));
}
private static char Replace(char arg, Dictionary<char, char> replacements)
{
if(replacements.ContainsKey(arg))
arg = replacements[arg];
return arg;
}
}
This method can be used as follows:
var rep = new Dictionary<char, char>
{
{ ')', '(' },
{ '(', ')' },
// { '#', '*' },
// { '*', '#' }
};
var c = str.ReplaceMultiple(rep);

Regex.Replace lets you process each Match (needs using System.Text.RegularExpressions;) :
string result = Regex.Replace(")Hi(", #"\(|\)", m => m.Value == "(" ? ")" : "(");
Alternative can be replacing one of the characters with something else:
string result = ")Hi(".Replace('(', '\0').Replace(')', '(').Replace('\0', ')');

Related

Extract multiple substring in the same line

I'm trying to build a logparser but i'm stuck.
Right now my program goes trough multiple file in a directory and read all the file line by line.
I was able to identify the substring i was looking for "fct=" and extract the value next to the "=" using delimiter but i notice that when i have a line with more then one "fct=" it doesnt see it.
So i restart my code and i find a way to get the index position of all occurence of fct= in the same line using an extension method that put the index in a list but i dont see how i can use this list to get the value next to the "=" and using my delimiter.
How can i extract the value next to the "=" knowing the start position of "fct=" and the delimiter at the end of the wanted value?
I'm starting in C# so let me know if i can give you more information.
Thanks,
Here's an example of what i would like to parse:
<dat>FCT=10019,XN=KEY,CN=ROHWEPJQSKAUMDUC FCT=666</dat></logurl>
<dat>XN=KEY,CN=RTU FCT=4515</dat></logurl>
<dat>XN=KEY,CN=RT</dat></logurl>
I would like t retrieve 10019,666 and 4515.
namespace LogParserV1
{
class Program
{
static void Main(string[] args)
{
int counter = 0;
string[] dirs = Directory.GetFiles(#"C:/LogParser/LogParserV1", "*.txt");
string fctnumber;
char[] enddelimiter = { '<', ',', '&', ':', ' ', '\\', '\'' };
foreach (string fileName in dirs)
{
StreamReader sr = new StreamReader(fileName);
{
String lineRead;
while ((lineRead = sr.ReadLine()) != null)
{
if (lineRead.Contains("fct="))
{
List<int> list = MyExtensions.GetPositions(lineRead, "fct");
//int start = lineRead.IndexOf("fct=") + 4;
// int end = lineRead.IndexOfAny(enddelimiter, start);
//string result = lineRead.Substring(start, end - start);
fctnumber = result;
//System.Console.WriteLine(fctnumber);
list.ForEach(Console.WriteLine);
}
// affiche tout les ligne System.Console.WriteLine(lineRead);
counter++;
}
System.Console.WriteLine(fileName);
sr.Close();
}
}
// Suspend the screen.
System.Console.ReadLine();
}
}
}
namespace ExtensionMethods
{
public class MyExtensions
{
public static List<int> GetPositions(string source, string searchString)
{
List<int> ret = new List<int>();
int len = searchString.Length;
int start = -len;
while (true)
{
start = source.IndexOf(searchString, start + len);
if (start == -1)
{
break;
}
else
{
ret.Add(start);
}
}
return ret;
}
}
}
You could simplify your code a lot by using Regex pattern matching instead.
The following pattern: (?<=FCT=)[0-9]* will match any group of digits preceded by FCT=.
Try it out
This enables us to do the following:
string input = "<dat>FCT=10019,XN=KEY,CN=ROHWEPJQSKAUMDUC FCT=666</dat></logurl>...";
string pattern = "(?<=FCT=)[0-9]*";
var values = Regex.Matches(input, pattern).Cast<Match>().Select(x => x.Value);
I have tested this solution with your data, and it gives me the expected results (10019,666 and 4515)
string data = #"<dat>FCT=10019,XN=KEY,CN=ROHWEPJQSKAUMDUC FCT=666</dat></logurl>
<dat>XN=KEY,CN=RTU FCT=4515</dat></logurl>
<dat>XN=KEY,CN=RT</dat></logurl>";
char[] delimiters = { '<', ',', '&', ':', ' ', '\\', '\'' };
Regex regex = new Regex("fct=(.+)", RegexOptions.IgnoreCase);
var values = data.Split(delimiters).Select(x => regex.Match(x).Groups[1].Value);
values = values.Where(x => !string.IsNullOrWhiteSpace(x));
values.ToList().ForEach(Console.WriteLine);
I hope my solution will be helpful, let me know.
Below code is usefull to extract the repeated words with linq in text
string text = "Hi Naresh, How are you. You will be next Super man";
IEnumerable<string> strings = text.Split(' ').ToList();
var result = strings.AsEnumerable().Select(x => new {str = Regex.Replace(x.ToLowerInvariant(), #"[^0-9a-zA-Z]+", ""), count = Regex.Matches(text.ToLowerInvariant(), #"\b" + Regex.Escape(Regex.Replace(x.ToLowerInvariant(), #"[^0-9a-zA-Z]+", "")) + #"\b").Count}).Where(x=>x.count>1).GroupBy(x => x.str).Select(x => x.First());
foreach(var item in result)
{
Console.WriteLine(item.str +" = "+item.count.ToString());
}
As always, break down the porblem into smaller bits. See if the following methods help in any way. Tying it up to your code is left as an excercise.
private const string Prefix = "fct=";
//make delimiter look up fast
private static HashSet<char> endDelimiters =
new HashSet<char>(new [] { '<', ',', '&', ':', ' ', '\\', '\'' });
private static string[] GetAllFctFields(string line) =>
line.Split(new string[] { Prefix });
private static bool TryGetValue(string delimitedString, out string value)
{
var buffer = new StringBuilder(delimitedString.Length);
foreach (var c in delimitedString)
{
if (endDelimiters.Contains(c))
break;
buffer.Append(c);
}
//I'm assuming that no end delimiter is a format error.
//Modify according to requirements
if (buffer.Length == delimitedString.Length)
{
value = null;
return false;
}
value = buffer.ToString();
return true;
}
Something like :
class Program
{
static void Main(string[] args)
{
char[] enddelimiter = { '<', ',', '&', ':', ' ', '\\', '\'' };
var fct = "fct=";
var lineRead = "fct=value1,useless text fct=vfct=alue2,fct=value3";
var values = new List<string>();
int start = lineRead.IndexOf(fct);
while(start != -1)
{
start += fct.Length;
int end = lineRead.IndexOfAny(enddelimiter, start);
if (end == -1)
end = lineRead.Length;
string result = lineRead.Substring(start, end - start);
values.Add(result);
start = lineRead.IndexOf(fct, end);
}
values.ForEach(Console.WriteLine);
}
}
You can split the line by string[]
char[] enddelimiter = { '<', ',', '&', ':', ' ', '\\', '\'' };
while ((lineRead = sr.ReadLine()) != null)
{
string[] parts1 = lineRead.Split(new string[] { "fct=" },StringSplitOptions.None);
if(parts1.Length > 0)
{
foreach(string _ar in parts1)
{
if(!string.IsNullOrEmpty(_ar))
{
if(_ar.IndexOfAny(enddelimiter) > 0)
{
MessageBox.Show(_ar.Substring(0, _ar.IndexOfAny(enddelimiter)));
}
else
{
MessageBox.Show(_ar);
}
}
}
}
}

Cleanup String: Replace consecutive nonalphanum Character with single seperator

I have a string, that need to be formatted:
keep alphanumeric letters
replace one or more non-aplhanum characters with a single separator
I came up with this:
string Format( string str , string separator )
{
if( string.IsNullOrEmpty( str ) )
return string.Empty;
var words = new List<string>();
var sb = new StringBuilder();
foreach( var c in str.ToCharArray() )
{
if( char.IsLetterOrDigit( c ) )
{
sb.Append( c );
}
else if( sb.Length > 0 )
{
words.Add( sb.ToString() );
sb.Clear();
}
}
if( sb.Any() )
words.Add( sb.ToString() );
return string.Join( seperator , words );
}
Is there a better/more-linq-like/shorter/more performant solution (without using regex) than this?
You could go to the "low level" and use the fact that a string is an IEnumerable<char> to use it's GetEnumerator
string Format(string str, string separator)
{
var builder = new StringBuilder (str.Length);
using (var e = str.GetEnumerator ())
{
while (e.MoveNext ())
{
bool hasMoved = true;
if (!char.IsLetterOrDigit (e.Current))
{
while ((hasMoved = e.MoveNext ()) && !char.IsLetterOrDigit (e.Current))
;
builder.Append (separator);
}
if (hasMoved)
builder.Append (e.Current);
}
}
return builder.ToString ();
}
Just in case here is a regex version too
private static readonly Regex rgx = new Regex(#"[^\w-[_]]+", RegexOptions.Compiled);
string Format (string str, string separator)
{
return rgx.Replace (str, separator);
}
Addendum regarding OP's comment about linq one-liner :
That's possible but hardly "easy to understand"
Using anonymous type
string Format (string str, string separator)
{
return str.Aggregate (new { builder = new StringBuilder (str.Length), prevDiscarded = false }, (state, ch) => char.IsLetterOrDigit (ch) ? new { builder = (state.prevDiscarded ? state.builder.Append (separator) : state.builder).Append (ch), prevDiscarded = false } : new { state.builder, prevDiscarded = true }, state => (state.prevDiscarded ? state.builder.Append (separator) : state.builder).ToString ());
}
Same thing using a Tuple instead
string Format (string str, string separator)
{
return str.Aggregate (Tuple.Create (new StringBuilder (str.Length), false), (state, ch) => char.IsLetterOrDigit (ch) ? Tuple.Create ((state.Item2 ? state.Item1.Append (separator) : state.Item1).Append (ch), false) : Tuple.Create (state.Item1, true), state => (state.Item2 ? state.Item1.Append (separator) : state.Item1).ToString ());
}
And with Tuple we can make some helpers to "ease" (so to speak) readability [although it's technically not a one-liner anymore]
//top of file
using State = System.Tuple<System.Text.StringBuilder, bool>;
string Format (string str, string separator)
{
var initialState = Tuple.Create (new StringBuilder (str.Length), false);
Func<State, StringBuilder> addSeparatorIfPrevDiscarded = state => state.Item2 ? state.Item1.Append (separator) : state.Item1;
Func<State, char, State> aggregator = (state, ch) => char.IsLetterOrDigit (ch) ? Tuple.Create (addSeparatorIfPrevDiscarded (state).Append (ch), false) : Tuple.Create (state.Item1, true);
Func<State, string> resultSelector = state => addSeparatorIfPrevDiscarded (state).ToString ();
return str.Aggregate (initialState, aggregator, resultSelector);
}
What makes it complex is that (IMO) Linq* is not really well suited when "item output" depend on previous (or next) items in the same collection
* Well Linq doesn't have a problem with that but it's quickly a lot of noise with Func and anonymous types/tuple syntax (maybe C#7.0 will change that a bit)
In the same flavor, one could also embrace side-effects which allow to have only the bool as state
string Format (string str, string separator)
{
var builder = new StringBuilder (str.Length);
Action<bool> addSeparatorIfPrevDiscarded = prevDiscarded => { if (prevDiscarded) builder.Append (separator); };
Func<bool, char, bool> aggregator = (prevDiscarded, ch) => {
if (char.IsLetterOrDigit (ch)) {
addSeparatorIfPrevDiscarded (prevDiscarded);
builder.Append (ch);
return false;
}
return true;
};
addSeparatorIfPrevDiscarded (str.Aggregate (false, aggregator));
return builder.ToString ();
}
Something like this to avoid the need for a List<string> and the use of string.Join. Also it will compile.
string Format(string str, char seperator)
{
if (string.IsNullOrEmpty(str))
return string.Empty;
var sb = new StringBuilder();
bool previousWasNonAlphaNum = false;
foreach (var c in str)
{
if (char.IsLetterOrDigit(c))
{
if (previousWasNonAlphaNum && sb.Count > 0)
sb.Append(seperator);
sb.Append(c);
}
previousWasNonAlphaNum = !char.IsLetterOrDigit(c);
}
return sb.ToString();
}
Try this, it will work
string Format(string str, string separator)
{
var delimiter = char.Parse(separator);
var replaced = false;
var cArray = str.Select(c =>
{
if (!char.IsLetterOrDigit(c) & !replaced)
{
replaced = true;
return delimiter;
}
else if (char.IsLetterOrDigit(c))
{
replaced = false;
}
else
{
return ' ';
}
return c;
}).ToArray();
return new string(cArray).Replace(" ","");
}
or you can try this one below
string Format(string str, string separator)
{
var delimiter = char.Parse(separator);
var cArray = str.Select(c => !char.IsLetterOrDigit(c) ? delimiter : c).ToArray();
var wlist = new string(cArray).Split(new string[]{separator}, StringSplitOptions.RemoveEmptyEntries);
return string.Join(separator, wlist);
}

Javascript slugifier to C#

I am looking at converting the JS slugify function by diegok and he is using this JavaScript construct:
function turkish_map() {
return {
'ş':'s', 'Ş':'S', 'ı':'i', 'İ':'I', 'ç':'c', 'Ç':'C', 'ü':'u', 'Ü':'U',
'ö':'o', 'Ö':'O', 'ğ':'g', 'Ğ':'G'
};
}
It is a map of char to char translations. However, I don't know which JS construct is this and how could it be rewritten in C# preferably without spending too much time on rewriting? (There's more to it, this is just one of the functions).
Should I make an array, dictionary, something else?
Dictionary<char, char> turkish_map() {
return new Dictionary<char, char> {
{'ş','s'}, {'Ş','S'}, {'ı','i'}, {'İ','I'} {'ç','c'} , {'Ç','C' }, {'ü','u'}, {'Ü','U'}, {'ö','o'}, {'Ö','O'}, {'ğ','g'}, {'Ğ','G'} };
}
The use it like:
turkish_map()['İ'] // returns I
Or you can save it into field and use it without creating it every time.
Use these methods to remove diacritics, the result will be sSıIcCuUoOgG.
namespace Test
{
public class Program
{
public static IEnumerable<char> RemoveDiacriticsEnum(string src, bool compatNorm, Func<char, char> customFolding)
{
foreach (char c in src.Normalize(compatNorm ? NormalizationForm.FormKD : NormalizationForm.FormD))
switch (CharUnicodeInfo.GetUnicodeCategory(c))
{
case UnicodeCategory.NonSpacingMark:
case UnicodeCategory.SpacingCombiningMark:
case UnicodeCategory.EnclosingMark:
//do nothing
break;
default:
yield return customFolding(c);
break;
}
}
public static IEnumerable<char> RemoveDiacriticsEnum(string src, bool compatNorm)
{
return RemoveDiacritics(src, compatNorm, c => c);
}
public static string RemoveDiacritics(string src, bool compatNorm, Func<char, char> customFolding)
{
StringBuilder sb = new StringBuilder();
foreach (char c in RemoveDiacriticsEnum(src, compatNorm, customFolding))
sb.Append(c);
return sb.ToString();
}
public static string RemoveDiacritics(string src, bool compatNorm)
{
return RemoveDiacritics(src, compatNorm, c => c);
}
static void Main(string[] args)
{
var str = "şŞıİçÇüÜöÖğĞ";
Console.Write(RemoveDiacritics(str, false));
// output: sSıIcCuUoOgG
Console.ReadKey();
}
}
}
For other characters like ı which wasn't converted, and others as you mentioned as #, ™ you can use the method to remove diacritics then use a regex to remove invalid characters. If you care enough for some characters you can make a Dictionary<char, char> and use it to replace them each one of them.
Then you can do this:
var input = "Şöme-p#ttern"; // text to convert into a slug
var replaces = new Dictionary<char, char> { { '#', 'a' } }; // list of chars you care
var pattern = #"[^A-Z0-9_-]+"; // regex to remove invalid characters
var result = new StringBuilder(RemoveDiacritics(input, false)); // convert Ş to S
// and so on
foreach (var item in replaces)
{
result = result.Replace(item.Key, item.Value); // replace # with a and so on
}
// remove invalid characters which weren't converted
var slug = Regex.Replace(result.ToString(), pattern, String.Empty,
RegexOptions.IgnoreCase);
// output: Some-pattern

String formatting using C#

Is there a way to remove every special character from a string like:
"\r\n 1802 S St Nw<br>\r\n Washington, DC 20009"
And to just write it like:
"1802 S St Nw, Washington, DC 20009"
To remove special characters:
public static string ClearSpecialChars(this string input)
{
foreach (var ch in new[] { "\r", "\n", "<br>", etc })
{
input = input.Replace(ch, String.Empty);
}
return input;
}
To replace all double space with single space:
public static string ClearDoubleSpaces(this string input)
{
while (input.Contains(" ")) // double
{
input = input.Replace(" ", " "); // with single
}
return input;
}
You also may split both methods into a single one:
public static string Clear(this string input)
{
return input
.ClearSpecialChars()
.ClearDoubleSpaces()
.Trim();
}
two ways, you can use RegEx, or you can use String.Replace(...)
Use the Regex.Replace() method, specifying all of the characters you want to remove as the pattern to match.
You can use the C# Trim() method, look here:
http://msdn.microsoft.com/de-de/library/d4tt83f9%28VS.80%29.aspx
System.Text.RegularExpressions.Regex.Replace("\"\\r\\n 1802 S St Nw<br>\\r\\n Washington, DC 20009\"",
#"(<br>)*?\\r\\n\s+", "");
Maybe something like this, using ASCII int values. Assumes all html tags will be closed.
public static class StringExtensions
{
public static string Clean(this string str)
{
string[] split = str.Split(' ');
List<string> strings = new List<string>();
foreach (string splitStr in split)
{
if (splitStr.Length > 0)
{
StringBuilder sb = new StringBuilder();
bool tagOpened = false;
foreach (char c in splitStr)
{
int iC = (int)c;
if (iC > 32)
{
if (iC == 60)
tagOpened = true;
if (!tagOpened)
sb.Append(c);
if (iC == 62)
tagOpened = false;
}
}
string result = sb.ToString();
if (result.Length > 0)
strings.Add(result);
}
}
return string.Join(" ", strings.ToArray());
}
}

How do I remove all non alphanumeric characters from a string except dash?

How do I remove all non alphanumeric characters from a string except dash and space characters?
Replace [^a-zA-Z0-9 -] with an empty string.
Regex rgx = new Regex("[^a-zA-Z0-9 -]");
str = rgx.Replace(str, "");
I could have used RegEx, they can provide elegant solution but they can cause performane issues. Here is one solution
char[] arr = str.ToCharArray();
arr = Array.FindAll<char>(arr, (c => (char.IsLetterOrDigit(c)
|| char.IsWhiteSpace(c)
|| c == '-')));
str = new string(arr);
When using the compact framework (which doesn't have FindAll)
Replace FindAll with1
char[] arr = str.Where(c => (char.IsLetterOrDigit(c) ||
char.IsWhiteSpace(c) ||
c == '-')).ToArray();
str = new string(arr);
1 Comment by ShawnFeatherly
You can try:
string s1 = Regex.Replace(s, "[^A-Za-z0-9 -]", "");
Where s is your string.
Using System.Linq
string withOutSpecialCharacters = new string(stringWithSpecialCharacters.Where(c =>char.IsLetterOrDigit(c) || char.IsWhiteSpace(c) || c == '-').ToArray());
The regex is [^\w\s\-]*:
\s is better to use instead of space (), because there might be a tab in the text.
Based on the answer for this question, I created a static class and added these. Thought it might be useful for some people.
public static class RegexConvert
{
public static string ToAlphaNumericOnly(this string input)
{
Regex rgx = new Regex("[^a-zA-Z0-9]");
return rgx.Replace(input, "");
}
public static string ToAlphaOnly(this string input)
{
Regex rgx = new Regex("[^a-zA-Z]");
return rgx.Replace(input, "");
}
public static string ToNumericOnly(this string input)
{
Regex rgx = new Regex("[^0-9]");
return rgx.Replace(input, "");
}
}
Then the methods can be used as:
string example = "asdf1234!##$";
string alphanumeric = example.ToAlphaNumericOnly();
string alpha = example.ToAlphaOnly();
string numeric = example.ToNumericOnly();
Want something quick?
public static class StringExtensions
{
public static string ToAlphaNumeric(this string self,
params char[] allowedCharacters)
{
return new string(Array.FindAll(self.ToCharArray(),
c => char.IsLetterOrDigit(c) ||
allowedCharacters.Contains(c)));
}
}
This will allow you to specify which characters you want to allow as well.
Here is a non-regex heap allocation friendly fast solution which was what I was looking for.
Unsafe edition.
public static unsafe void ToAlphaNumeric(ref string input)
{
fixed (char* p = input)
{
int offset = 0;
for (int i = 0; i < input.Length; i++)
{
if (char.IsLetterOrDigit(p[i]))
{
p[offset] = input[i];
offset++;
}
}
((int*)p)[-1] = offset; // Changes the length of the string
p[offset] = '\0';
}
}
And for those who don't want to use unsafe or don't trust the string length hack.
public static string ToAlphaNumeric(string input)
{
int j = 0;
char[] newCharArr = new char[input.Length];
for (int i = 0; i < input.Length; i++)
{
if (char.IsLetterOrDigit(input[i]))
{
newCharArr[j] = input[i];
j++;
}
}
Array.Resize(ref newCharArr, j);
return new string(newCharArr);
}
I´ve made a different solution, by eliminating the Control characters, which was my original problem.
It is better than putting in a list all the "special but good" chars
char[] arr = str.Where(c => !char.IsControl(c)).ToArray();
str = new string(arr);
it´s simpler, so I think it´s better !
Here's an extension method using #ata answer as inspiration.
"hello-world123, 456".MakeAlphaNumeric(new char[]{'-'});// yields "hello-world123456"
or if you require additional characters other than hyphen...
"hello-world123, 456!?".MakeAlphaNumeric(new char[]{'-','!'});// yields "hello-world123456!"
public static class StringExtensions
{
public static string MakeAlphaNumeric(this string input, params char[] exceptions)
{
var charArray = input.ToCharArray();
var alphaNumeric = Array.FindAll<char>(charArray, (c => char.IsLetterOrDigit(c)|| exceptions?.Contains(c) == true));
return new string(alphaNumeric);
}
}
If you are working in JS, here is a very terse version
myString = myString.replace(/[^A-Za-z0-9 -]/g, "");
I use a variation of one of the answers here. I want to replace spaces with "-" so its SEO friendly and also make lower case. Also not reference system.web from my services layer.
private string MakeUrlString(string input)
{
var array = input.ToCharArray();
array = Array.FindAll<char>(array, c => char.IsLetterOrDigit(c) || char.IsWhiteSpace(c) || c == '-');
var newString = new string(array).Replace(" ", "-").ToLower();
return newString;
}
There is a much easier way with Regex.
private string FixString(string str)
{
return string.IsNullOrEmpty(str) ? str : Regex.Replace(str, "[\\D]", "");
}

Categories