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

守給你的承諾、 提交于 2019-12-12 00:58:27

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/55675415/for-a-string-containing-characters-and-numbers-how-to-add-1-to-all-numbers-only

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!