user3924730
user3924730

Reputation: 183

How to know if string contains more than one same word

I have a string which is like this ..String s=and oc='LOCAL' and oc='STD' and oc='ISD' and oc='INC'.Now as per my requirement if this string contains more than one and then i have to replace all other and with or except first and else it should be the same string only..

Please help me how to get to know about more than one and and how to replace all other and except first one.

I am trying to get this using replace but i am not getting it exactly..

Please help me..

Upvotes: 0

Views: 670

Answers (2)

Shell
Shell

Reputation: 6849

you code do like this

int iCount = myString.Split( new string[] {"and"}
                           , StringSplitOptions.None )
                     .Length -1;

Try it on this fiddle. https://dotnetfiddle.net/6pcnz3

Upvotes: 1

Noctis
Noctis

Reputation: 11763

Doesn't sound like you've put much effort in, but here are 2 options:

  1. Use string.IndexOf to get the index of your first and, and from there, cut the rest, and then use string.Replace to change and to or
  2. Use linq. Split on white space. You can then have a list of words, and then you can replace all the ands that aren't the first to or.

Upvotes: 4

Related Questions