简体   繁体   中英

For a string containing characters and numbers, how to add 1 to all numbers only

Thanks for helping me! I have a string list coming from a path file:

Data="M311.97458,250.39993 L213.97533,248.39996 222.37435,216.7998 C222.37435,216.7998 ......589.5753,173.99994 593.1753,179.9999 ......334.3039,253.21373 311.97458,250.39993 z" (the "......." is used for representing uncessary number")

As you can see, the characters (like "M" and "C") have some special meaning, and number pairs are for cooridinate. I want to add 1 to each numbers in "Data" without changing any other things. How can I do that with C#? I guess a .split() is useful but the "Data" is too hard for .split() only

Thank you!

You can use Regex to identify the numbers within the string and replace them with a new value. For example;

var data = @"M311.97458,250.39993 L213.97533,248.39996 222.37435,216.7998 C222.37435,216.7998 ......589.5753,173.99994,593.1753,179.9999......334.3039,253.21373 311.97458,250.39993 z";            
var replaced = Regex.Replace(data, "((?=[^, ])\\d+\\.\\d+)", (match) => (double.Parse(match.Value) + 1).ToString());
// output: M312.97458,251.39993 L214.97533,249.39996 223.37435,217.7998 C223.37435,217.7998 ......590.5753,174.99994,594.1753,180.9999......335.3039,254.21373 312.97458,251.39993 z

So here the Regex pattern is identifying the numbers within the string by finding anything that's not a comma or space and is numeric with a decimal place in (so it won't work for integers, but you can adapt if required). Then effectively in the Regex.Replace we're looping through each match, and using a MatchEvaluator to add one to the number and return it to form the new string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM