Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to separate 1 string into multiple strings [duplicate]

Tags:

string

c#

How do I convert "ThisIsMyTestString" into "This Is My Test String" using C#?

Is there a fast way to do it?

I've been thinking of a pseudo code but it's complicated and ugly:

String s = "ThisIsMyTestString";

List<String> strList = new List<String>();
for(int i=0; i < str->Length ; i++)
{
   String tmp = "";
   if (Char.IsUpper(str[i]))
   {
     tmp += str[i];
     i++;
   }

   while (Char::IsLower(str[i]))
   {
     tmp += str[i];
     i++;
   }

   strList .Add(tmp);
}

String tmp2 = "";
for (uint i=0 ; i<strList.Count(); i++)
{
  tmp2 += strList[i] + " ";
}
like image 390
Dardar Avatar asked Jun 13 '26 10:06

Dardar


2 Answers

You can use Regex as outlined here:

Regular expression, split string by capital letter but ignore TLA

Your regex: "((?<=[a-z])[A-Z]|A-Z)"

Find and replace with " $1"

string splitString = Replace("ThisIsMyTestString", "((?<=[a-z])[A-Z]|[A-Z](?=[a-z]))", " $1")

Here (?<=...) is a "positive lookbehind, a regex that should precede the match. In this case the lookbehind is "characters 'a' through 'z'" (?=...) is a similar construct with lookahead, where the match has to be followed by regex-described string. In this case the lookahead is "characters 'a' through 'z'" In both cases the final match contains one character "A" through "Z" followed by 'a'-'z' OR one character 'a' through 'z' followed by a capital letter. Replacing these matches puts a space between the capital and lowercase letters

like image 174
Sten Petrov Avatar answered Jun 16 '26 08:06

Sten Petrov


Not best code, but it works

String.Join("", s.Select(c => Char.IsUpper(c) ? " " + c : c.ToString())).Trim()
like image 24
Sergey Berezovskiy Avatar answered Jun 16 '26 07:06

Sergey Berezovskiy