亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

字符串的 char 值更改為 Int

字符串的 char 值更改為 Int

C#
慕斯709654 2022-01-09 10:49:22
我正在處理一個與字符串相關的問題,其中也存在少量數字。我的工作是迭代所有字符,識別這些數字并執行算術運算。最后返回修改后的字符串。但是對于此操作,所有字符都更改為 Int。謝謝string str="Please Change 2015";string str2=String.Join("", str.Select(x=> (x >= '0' && x <= '9') ?'9'-x: x).ToList()); Given Output: 8010810197115101326710497110103101327984Required Output: Please Change 7984
查看完整描述

2 回答

?
收到一只叮咚

TA貢獻1821條經驗 獲得超5個贊

要不就


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 

+'0' // convert it back to a char 

(char) // make sure we output characters again


查看完整回答
反對 回復 2022-01-09
?
慕尼黑的夜晚無繁華

TA貢獻1864條經驗 獲得超6個贊

StringBuilder對我來說,這聽起來像是一份工作。附加每個非數字字符,對每個數字字符執行數學運算,最后輸出完整字符串。


注意:這假設您不應該修改輸入字符串,而是返回一個新字符串。


請參閱我的 repl或下面粘貼的代碼。


using System;

using System.Text;

using System.Linq;


class MainClass {

  public static void Main (string[] args) {

    const string testcase = "Please Change 7984";

    const string input = "Please Change 2015";

    var builder = new StringBuilder();


    input.ToList<Char>().ForEach(c => {

        if ('0' <= c && c <= '9')

            builder.Append('9' - c);

        else

            builder.Append(c);

    });


    var output = builder.ToString();

    var success = (testcase == output);


    Console.WriteLine($"output: {output}");

    Console.WriteLine($"success: {success}");

  }

}

輸出:


>>> Mono C# compiler version 4.0.4.0

>>> output: Please Change 7984

>>> success: True


查看完整回答
反對 回復 2022-01-09
  • 2 回答
  • 0 關注
  • 156 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號