6

I have a string:

"Hello 7866592 this is my 12432 string and 823 i need to flip all 123"

And i want to to be

"Hello 2956687 this is my 23421 string and 328 i need to flip all 321"

I use this regular expression to get all numbers:

Regex nums = new Regex("\d+");
3
  • One should look into String.Split and reversing strings Commented Jun 21, 2012 at 18:49
  • There are no normal regular expression language elements that will do this for you. You don't say whether you need the solution to be a regular expression (and that would be a very long and difficult regex, if you can even do it). That means you seem to be looking for a normal programming solution for a basic problem. I don't think this is appropriate for stackoverflow. Commented Jun 21, 2012 at 18:49
  • Sounds like homework. Using regular expressions would be good to extract the numbers, but I reckon it'd be best to just increment through the string as an array of chars, record an index point where a set of digits start, then increment until you reach a non-digit, then look at reversing the digits in between index points a and b-1. Commented Jun 21, 2012 at 18:51

2 Answers 2

21
var replacedString = 
    Regex.Replace(//finds all matches and replaces them
    myString, //string we're working with
    @"\d+", //the regular expression to match to do a replace
    m => new string(m.Value.Reverse().ToArray())); //a Lambda expression which
        //is cast to the MatchEvaluator delegate, so once the match is found, it  
        //is replaced with the output of this method.
Sign up to request clarification or add additional context in comments.

5 Comments

The important bit here is the replacer function. (Just be glad this isn't Java!)
Error: Cannot convert lambda expression to type 'string'
@Danpe sorry fixed, meant to do the Regex.Replace, but was typing in a browser.
Man, you are just awesome! I whould like if you can add explenation of how it works exactly :)
+1. Couldn't haven written it better myself. This overload of Regex.Replace utilizes the MatchEvaluator, which allows you to perform any operation you'd like on each individual match.
1

Split the string on spaces. Then take the strings in the new string array that are digits and run this function on them:

public static string Reverse( string s )
{
   char[] charArray = s.ToCharArray();
   Array.Reverse( charArray );
   return new string( charArray );
}

Then recombine your array into a single string.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.