strings and spaces

R

RobcPettit

Hi, Ive been breaking down my string with regex and havnt been doing
to bad for a begginer. However Im struggling now. Examole string = '10
04 thismaybemissing 10 rob 1 2 3 robagain 3 74 * 70 4 2' This is
normally how the string turns out. Now and again the
'thismaybemissing' is missing giving me '10 04 10 rob 1 2 3 robagain 3
74 * 70 4 2'. So now I want to insert a word after the second space in
the string, when I try using regex I end up inserting words between
the spaces between all the numbers understandably as Im usinf /d/s/d.
Is there a way to say 'after second space insert....
Regards Robert
 
J

Jon Skeet [C# MVP]

(Apologies if another version of this arrives - I cancelled it just as
it was posting...)

Hi, Ive been breaking down my string with regex and havnt been doing
to bad for a begginer. However Im struggling now. Examole string = '10
04 thismaybemissing 10 rob 1 2 3 robagain 3 74 * 70 4 2' This is
normally how the string turns out. Now and again the
'thismaybemissing' is missing giving me '10 04 10 rob 1 2 3 robagain 3
74 * 70 4 2'. So now I want to insert a word after the second space in
the string, when I try using regex I end up inserting words between
the spaces between all the numbers understandably as Im usinf /d/s/d.
Is there a way to say 'after second space insert....

Well, the easiest way is to use:

int firstSpace = text.IndexOf(' ');
int secondSpace = text.IndexOf(' ', firstSpace+1);
text = text.Insert(secondSpace, "word");

You should test the firstSpace and secondSpace values for potentially
being -1 as you go, in case there aren't two spaces...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top