the string class has a function
string.Replace(oldchar,new char)
which replaces all the occurrences of that char with new char, if that is what you want then no need to check the index of the chars.
For Each c As Char In BadChar
If Input.IndexOf(c) >= 0 Then
Input = Input.Replace(c, "")
End If
Next
In the above code you are replacing a char with a empty string. This is not allowed (as CTS is common for all .net languages). What you need to do is change your char array to string array then use the
Input.Replace(",","");
in the array loop of the bad chars/strings
Improved answer
-----------------
Note: My vb conversion may not be accurate, the C# would be fine.
First let me give you an example for remove punctuation.
can define limited array as
string[] BadChar=new string[5]{",", ":", ";", ".", "'"};
,
Dim BadChar() As String = New String() {",", ":", ";", ".", "'"}
(in vb).
public string removePunctuation(string input, string[] badChars)
{
StringBuilder sb = new StringBuilder();
sb.Append(input);
foreach (string badChar in badChars)
{
sb.Replace(badChar, "");
}
return sb.ToString();
}
I am using string builder here as it is holds a mutable string. Trying Vb conversion now.
Function removePunctuation(ByVal Input As String, ByVal BadChar As String()) As String
Dim sb as new StringBuilder()
sb.Append(Input);
ForEach badChar as string In badChars
sb.Replace(badChar,"")
End
Return sb.Tostring()
End Function
Now answers for your comment.
I asked to use a string array, because the signature of the
Replace
function has either
Replace(oldchar, newchar)
or
Replace(oldstring,newstring)
and not
Replace(oldchar,newstring)
. In you loop you are getting a char, but trying to replace with a string as here
Input = Input.Replace(c, "")
. That was wrong.
Second thing the chars has to be enclosed with a single quote. Not double quote. In your code
Dim BadChar() As Char = New Char() {",", ":", ";", ".", "'"}
was like this. I am not sure VB allow this, but yet not preferable way. Though you change it to single quotes then for the char "'" you need to use an escape character like
'\''
. That will again confuse you. So that I asked simply use a string array of punctuation marks.
Hope it is clear now.
try my example.