猿问

字符串的 char 值更改为 Int

我正在处理一个与字符串相关的问题,其中也存在少量数字。我的工作是迭代所有字符,识别这些数字并执行算术运算。最后返回修改后的字符串。但是对于此操作,所有字符都更改为 Int。


谢谢


string str="Please Change 2015";

string str2=String.Join("", str.Select(x=> (x >= '0' && x <= '9') ?'9'-x: x).ToList()); 


Given Output: 8010810197115101326710497110103101327984

Required Output: Please Change 7984


慕斯709654
浏览 135回答 2
2回答

收到一只叮咚

要不就string str = "Please Change 2015";string str2 = String.Join("", str.Select(x => char.IsDigit(x) ? (char)(9-(x-'0')+'0') : x).ToList());输出Please Change 7984解释-'0' // convert it from char to a number&nbsp;+'0' // convert it back to a char&nbsp;(char) // make sure we output characters again

慕尼黑的夜晚无繁华

StringBuilder对我来说,这听起来像是一份工作。附加每个非数字字符,对每个数字字符执行数学运算,最后输出完整字符串。注意:这假设您不应该修改输入字符串,而是返回一个新字符串。请参阅我的 repl或下面粘贴的代码。using System;using System.Text;using System.Linq;class MainClass {&nbsp; public static void Main (string[] args) {&nbsp; &nbsp; const string testcase = "Please Change 7984";&nbsp; &nbsp; const string input = "Please Change 2015";&nbsp; &nbsp; var builder = new StringBuilder();&nbsp; &nbsp; input.ToList<Char>().ForEach(c => {&nbsp; &nbsp; &nbsp; &nbsp; if ('0' <= c && c <= '9')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; builder.Append('9' - c);&nbsp; &nbsp; &nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; builder.Append(c);&nbsp; &nbsp; });&nbsp; &nbsp; var output = builder.ToString();&nbsp; &nbsp; var success = (testcase == output);&nbsp; &nbsp; Console.WriteLine($"output: {output}");&nbsp; &nbsp; Console.WriteLine($"success: {success}");&nbsp; }}输出:>>> Mono C# compiler version 4.0.4.0>>> output: Please Change 7984>>> success: True
随时随地看视频慕课网APP
我要回答