Home > OS >  how to get before and after text in the string which contains 'Or' in it
how to get before and after text in the string which contains 'Or' in it

Time:10-14

I want a code that takes a string with 'Or' in it and takes text before and after 'Or' and stores it in seperate variable

I tried the substring function

var text = "Actor or Actress";
var result= text.Substring(0, text.LastIndexOf("or"));

but with this getting only actor I want actor as well as actress but in seperate variables as a whole word so it can be anything in place of 'actor or actress'

CodePudding user response:

You need to use one of the flavors of String.Split that accepts an array of string delimiters:

string text = "Actor or Actress";
string[] delim = new string[] { " or " };   // add spaces around to avoid spliting `Actor` due to the `or` in the end
string[] elements = text.Split(delim, StringSplitOptions.None);
foreach (string elem in elements)
{
    Console.WriteLine(elem);
}

Output:

Actor
Actress

Note: I am using .NET framework 4.8, but .NET 6 also has an overload of String.Split that accepts a single string delimiter so there's no need to create delim as an array of strings, unless you want to be able to split based on variations like " Or "," or ".

CodePudding user response:

Spli() should do the job

   text.Split(“or”);

CodePudding user response:

use the Split() method

var text = "Actor or Actress";
Console.WriteLine(text.Split("or")[0]);
Console.WriteLine(text.Split("or")[1]);

Output

Actor 
Actress

CodePudding user response:

try this

string[] array = text.Split(' ');
foreach (string item in array)
{
    if (item != "or")
    {
        Console.WriteLine(item);
    }
}

Output

Actor 
Actress
  • Related