Strings again...

Mothra

Well-known member
Joined
Nov 26, 2002
Messages
173
Location
Fresno, California
Alright, Im stuck once more. Heres the deal. Im trying to iterate through a string and replace certain parts that are marked with a special character. The problem is that I dont want to do a general .Replace, I want to read through the string and as I come to the marked position, I want to replace the character directly following the marker with a value from an array. I guess what I really want is similar functionality to Mid() in good old VB 6 (something that will let me specify the position where the replacment should take place). Am I out of luck?

Help me Obi Wan...youre my only hope...
 
first look at the String class, it would be really helpful if you give me/us an example so we can tell you an algorythm, if you dont want to use replace then you have to work with substring i think
 
Example...

I guess that WOULD help a little....

The string Im be using would look like this, The characters I want to replace are preceded by a ~

this wouls be taken out of a richTextBox

~A ~B ~C ~D
This is some sample text
~E ~F ~G ~H
This is some sample text

(the real string will be formatted just like this but have many more lines...)

and assigned to a string variable

C#:
string myString = richTextBox1.Text;

I want to replace the ~A, ~B, ~C and ~D(...) with values from an array, call it
C#:
string[] values;

The ~A would be replaced by values[0], the ~B would become values[1] and so on...The only trouble Im having is getting the values into myString. Doing a blanked .Replace has the possibility of re-converting a character so I really need to run through the string and replace them as I come to them.
 
C#:
string text = " .... ";

for (int i=0; i < text.Length; i++)
{
    if (text.Chars[i] == ~)
        text = text.Substring(0, i) + values[i] + text.Substring(i+1);
}

i didnt test it, but tell me if any error occurs
 
String does not have a .Chars[]...I think, though, if I convert the string to a char[] and then iterate through the char[] and replace the individual characters as I come to them. Im trying to make that work right now....
 
Use the Regex.Replace method to find and exchange your ~X code. Youll need one for each code you want to swap. I dont see a reason to iterate through the string letter by letter if you use this route.
 
Ill check that out but, I did find a solution. I converted the string into a character array and that seemed to do the trick. I might play with the Regex.Replace but, since I got the logic to work with the char[] Im not sure Ill change it now... Thank you both for all your help!
 
Back
Top