-3

I'm working on an interesting project that requires some string replacement in a unusual way. Specifically, the result's case must try to match the original's case and the search itself is case insensitive.

Examples:

original: "Test Foobar Test" search for: "foobar" replace with: "helloworld" result: "Test Helloworld Test"

original: "Test FOOBAR Test" search for: "foobar" replace with: "helloworld" result: "Test HELLOWORLD Test"

Now, I realize there are many cases where this would be hard to determine (mixed case match with a different length replacement.) But what if I restricted it to three cases: All caps, all lowercase, and first letter capitalized?

So far, my plan is to do three searches: First do a case sensitive search for the all caps condition, then a case sensitive search for the first letter condition, and finally a case insensitive search and replace with all lowercase. But I'd like something faster and more elegant if possible. Any ideas?

Danation
  • 743
  • 8
  • 20
  • 2
    What about test FooBar, should that yield HelloWorld? Have you tried any of the string manipulation functions? – Ross Bush Feb 15 '15 at 01:05
  • @lrb In a perfect world, FooBar would yield HelloWorld, but I can't think of a way to make that work. So that's why I'm restricting it to the three specified cases. So FooBar would yield Helloworld. – Danation Feb 15 '15 at 01:15
  • @EZI I explained my current solution, which is very simple and needs no code to be understood. – Danation Feb 15 '15 at 01:16

2 Answers2

1

I would use a regex to do the find, because:

  • the regex can be made case insensitive
  • the regex can return a collection of matches that it found, you can examine each match individually
  • the action you take can be specific to each match, one might be camel case while another is all uppercase

A good solution could be to encapsulate the action to take as a method, then iterate over the found matches, call the method, replace the match with the new text.

If you are intending to keep the capitalization of the replacement simple then you could check just the first alpha character and one other arbitrary one - if both are uppercase the assume the result should be uppercase, if the first is upper but second lower then assume camel casing, if both are lower then assume all lowercase. Of course you can increase the number of characters to test if two is too crude to be reliable.

slugster
  • 49,403
  • 14
  • 95
  • 145
  • I couldn't find a way to replace based on a collection of matches, but I did find an overload of Regex.Replace that has a MatchEvaluator. – Danation Feb 15 '15 at 03:56
0

I found an overload of Regex.Replace that takes a MatchEvaluator. In the evaluator, I can check the matched string's capitalization and go from there.

Also, as slugster said, Regex methods have an option for case insensitivity.

Danation
  • 743
  • 8
  • 20