How could I replace certain letters of a string with diferent ones without useing a lot of if statments. So just replace each letter or number with a diferent character. Any suggestions would be nice.
Printable View
How could I replace certain letters of a string with diferent ones without useing a lot of if statments. So just replace each letter or number with a diferent character. Any suggestions would be nice.
However, I can't see the solution being as simple as that. If I misunderstood, please can you explain in a bit more detail, perhaps with an example of a "before" and "after" string?Code:String.Replace("a", "!")
String.Replace ("3","f")
String.Replace ("S","g")
....
That is a little bit vague. Is it intended to be a code of sorts (eg. ROT-13) or should the replacements be random? Do you want to stick with alphanumerics or will any character do?
What Espanolita said would work, and I could do that. But is there a way to make that easier? without haveing to do every character you wish to replace
?
Well that's why I asked if random replacement was acceptable. If you want a specific replacement for each character then at some point you're going to need to define each one unless there is some kind of 'formula' (such as ROT-13) that can be applied. It really would help to have an idea of what this procedure is meant to acheive.
Just use String.Replace()
Example:
Code:Dim str As String = "Here is your sentence."
Return str.Replace("e", "3") ' will output "H3r3 is your s3nt3nc3."
Or you could try something like:
if you have to replace a lot of characters in a long string (will only scan the source-string once, but has the overhead of creating a sorted list).vb.net Code:
'Will replace any occurence of a character in replace_chars with index i that is present in source 'with the corresponding character in replace_with at index i. 'Thus "Abe Lincoln", "AaEeLl", "443311" will result in "4b3 1inco1n" Private Function replace(source As String, replace_chars As String, replace_with As String) As String If replace_chars.Length <> replace_with.Length Then Return String.Empty 'ERROR Dim d As New SortedList(Of Char, Char) For i As Integer = 0 To replace_chars.Length - 1 d.Add(replace_chars(i), replace_with(i)) Next Return String.Concat(source.Select(Function(c) If(d.ContainsKey(c), d(c), c))) End Function
Usage:
TomCode:MessageBox.Show(replace("Abe Lincoln", "AaEeLl", "443311"))