views:

458

answers:

3

That's what I've written so far:

string omgwut;
omgwut = textBox1.Text;
omgwut = omgwut.Replace(" ", "snd\\space.wav");
omgwut = omgwut.Replace("a", "snd\\a.wav");

Now, the problem is that this code would turn

"snd\space.wav"

into

"snd\spsnd\a.wavce.wsnd\a.wavv"

in line four. Not what I'd want! Now I know I'm not good at C#, so that's why I'm asking.

Solutions would be great! Thanks!

+1  A: 

The problem is that you are doing multiple passes of the data. Try just stepping through the characters of the string in a loop and replacing each 'from' character by its 'to' string. That way you're not going back over the string and re-doing those characters already replaced.

Also, create a separate output string or array, instead of modifying the original. Ideally use a StringBuilder, and append the new string (or the original character if not replacing this character) to it.

Phil H
+3  A: 

You'll still need to write the getSoundForChar() function, but this should do what you're asking. I'm not sure, though, that what you're asking will do what you want, i.e., play the sound for the associated character. You might be better off putting them in a List<string> for that.

StringBuilder builder = new StringBuilder();
foreach (char c in textBox1.Text)
{
    string sound = getSoundForChar( c );
    builder.Append( sound );
}
string omgwut = builder.ToString();

Here's a start:

public string getSoundForChar( char c )
{
     string sound = null;
     if (sound == " ")
     {
         sound = "snd\\space.wav";
     }
     ... handle other special characters
     else
     {
         sound = string.Format( "snd\\{0}.wav", c );
     }
     return sound;
}
tvanfosson
The type or namespace name 'StringBuilder' could not be found (are you missing a using directive or an assembly reference?)
a2h
add "using System.Text;" at the top of the file.
atsjoo
And I thought I was good at figuring out what people mean when they ask questions. I'm impressed you understood what he was really asking.
Jim Mischel
A: 

I do not know of a way to simultaneously replace different characters in C#.

You could loop over all characters and build a result string from that (use a stringbuilder if the input string can be long). For each character, you append its replacement to the result string(builder).

But what are you trying to do? I cannot think of a useful application of appending file paths without any separator.

Renze de Waal