741

Custom function for splitting string on Upper Case characters does not works as expected

public static string UpperCaseStringSplitter(string stringToSplit) { var stringBuilder = new StringBuilder(); foreach (char c in stringToSplit) { if (Char.IsUpper(c) && stringToSplit.IndexOf(c) > 0) stringBuilder.Append(" " + c); else stringBuilder.Append(c); } return stringBuilder.ToString(); }

If I pass a string like this:

TestSrak

the output is the expected one : "Test Srak".

But when there are two same letters where one is lower case and the other is Uppercase next to each other, the split does not happen:

For example If the input is:

TestTruck

The output is also TestTruck . Can You please tell me where is the problem and how can I fix it. Thanks!

Answer1:

The problem is this

stringToSplit.IndexOf(c) > 0)

In "TestTruck" the first letter(index == 0) is also a T, therefore it will not enter the if.

Instead i would use a for-loop and check if the current char is the first, then you can skip the split:

for(int i=0; i < stringToSplit.Length; i++) { if (i > 0 && Char.IsUpper(stringToSplit[i])) stringBuilder.Append(" ").Append(stringToSplit[i]); else stringBuilder.Append(stringToSplit[i]); }

Answer2:

Try this:

public static string UpperCaseStringSplitter(string stringToSplit) { var stringBuilder = new StringBuilder(); for(int i = 0; i <stringToSplit.Length; i++) { char c = stringToSplit[i]; if (Char.IsUpper(c) && i > 0) stringBuilder.Append(" " + c); else stringBuilder.Append(c); } return stringBuilder.ToString(); }

Answer3:

The problem with your code has been identified by Tim Schmelter's answer, but if you are trying to append a space before the upper case character in the string, then you can try the following (using LINQ)

string str = "TestTrak"; string newString = string.Join("", str.Select(r=> char.IsUpper(r) ?" " + r: r.ToString())); newString = newString.Trim(); //to remove space from the start

Answer4:

Try this:

if (string.IsNullOrWhiteSpace(stringToSplit)) return stringToSplit; var stringBuilder = new StringBuilder(); for (int i = 0; i < stringToSplit.Length; i++) { if (Char.IsUpper(stringToSplit[i])) { stringBuilder.Append(" "); } stringBuilder.Append(stringToSplit[i]); } return stringBuilder.ToString().Trim();

Recommend

  • How to make a npm command, that executes two commands in the console (one after another)?
  • substitute period from abbreviation (single letter + period) unless followed by a capital letter
  • Failed to create any app request
  • Grouping by blank nodes
  • Xamarin iOS debugger not hitting breakpoints
  • R DataTable Join and constrain rows
  • PHP file_exists() anomaly
  • Entity Framework ObjectContext: Concurrency
  • Accessing the variables from a PHP Anonymous Function
  • Losing my session variables
  • Why can't UI components be accessed from a backgroundworker?
  • Problem with Django using Apache2 (mod_wsgi), Occassionally is “unable to import from module” for no
  • How to make R's read_csv2() recognise the text characters properly
  • Who propagate bugfixes across branches (corporate development)?
  • Jenkins: FATAL: Could not initialize class hudson.util.ProcessTree$UnixReflection
  • PHP buffered output depending on server setting?
  • Functions in global context
  • Scrapy recursive link crawler
  • CSS Linear-gradient formatting issue accross different browsers
  • Display issues when we change from one jquery mobile page to another in firefox
  • Deselecting radio buttons while keeping the View Model in synch
  • Is possible to count alias result on mysql
  • Check if a string to interpolate provides expected placeholders
  • Deserializing XML into class C#
  • Javascript convert timezone issue
  • JSON with duplicate key names losing information when parsed
  • Jquery - Jquery Wysiwyg return html as a string
  • Function pointer “assignment from incompatible pointer type” only when using vararg ellipsis
  • Matrix multiplication with MKL
  • -fvisibility=hidden not passed by compiler for Debug builds
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • apache spark aggregate function using min value
  • python draw pie shapes with colour filled
  • Django query for large number of relationships
  • Why is Django giving me: 'first_name' is an invalid keyword argument for this function?
  • Binding checkboxes to object values in AngularJs
  • How to Embed XSL into XML
  • How can I use `wmic` in a Windows PE script?
  • How to push additional view controllers onto NavigationController but keep the TabBar?