-1

I would like to split a string only after the first word which has more than two spaces b/w them. For example:

string myString = "AAAA AAA DDD    BBBB BBB BBB        CCCCCCCC";

I want to split it into these:

"AAAA AAA DDD"   
"BBBB BBB BBB        CCCCCCCC"

Please help.

User2309
  • 35
  • 1
  • 5

2 Answers2

5

Substring is the simplest way:

string myString = "AAAA AAA DDD    BBBB BBB BBB        CCCCCCCC";
int splitIndex = myString.IndexOf("  ");
if (splitIndex > 0)
{
    Console.WriteLine(myString.Substring(0, splitIndex).Trim());
    Console.WriteLine(myString.Substring(splitIndex).Trim());
}
else
    throw new FormatException();
Zein Makki
  • 29,485
  • 6
  • 52
  • 63
0

Another option is to use Regex:

string myString = "AAAA AAA DDD    BBBB BBB BBB        CCCCCCCC";   
Regex searchTerm = new Regex("[ ]{2,}", RegexOptions.None);


var splitedData = searchTerm.Replace(myString, "|").Split(new string[]{"|"},StringSplitOptions.RemoveEmptyEntries);

foreach(var d in splitedData)
{
    Console.WriteLine("{0}", d);
}

Result:

AAAA AAA DDD
BBBB BBB BBB
CCCCCCCC

My solution is based on this: How do I replace multiple spaces with a single space in C#?

Maciej Los
  • 8,468
  • 1
  • 20
  • 35