簡體   English   中英

如何替換ac#字符串中的特定字符?

[英]How do I replace specific characters from a c# string?

如果我有以下字符串:“ user:jim; id:23; group:49st;” 我如何用其他內容替換組代碼(49st),以便顯示:“ user:jim; id = 23; group:76pm;”

抱歉,如果問題很簡單,但我沒有找到具體答案,只是與我的情況不同。

您可以像這樣使用“組”的索引

string s = "user:jim;id:23;group:49st;";
string newS = s.Substring(0,s.IndexOf("group:") + 6);
string restOfS = s.IndexOf(";",s.IndexOf("group:") + 6) + 1 == s.Length 
? "" 
: s.Substring(s.IndexOf(";",s.IndexOf("group:") + 6) + 1);
newS += "76pm;";
s = newS + restOfS;

符合s = criteria ? true : false s = criteria ? true : false本質上是一個if,但是使用三元運算符將其放在一行上。

另外,如果您知道已經有哪些文本以及應將其替換為哪種文本,則可以使用“ Replace

s = s.Replace("49st","76pm");

作為附加的預防措施,如果您並非總是要在字符串中包含此“ group:”部分,為避免錯誤,請將其放在if首先檢查的if

if(s.Contains("group:"))
{
    //Code
}

使用正則表達式查找匹配項,並將其替換為原始字符串中的新值,如下所述:

string str = "user:jim;id=23;group:49st;";
var match = Regex.Match(str, "group:.*;").ToString();
var newGroup = "group:76pm;";
str = str.Replace(match, newGroup);

無論組在字符串中的何處出現,此解決方案都應該起作用:

string input = "user:jim;id:23;group:49st;"; 
string newGroup = "76pm";
string output = Regex.Replace(input, "(group:)([^;]*)", "${1}"+newGroup);

這是一種非常通用的方法,用於拆分輸入,更改項目,然后將項目重新連接到字符串。 在您的示例中,它並不是要進行單個替換,而是要顯示如何拆分和合並字符串中的項目。

我使用正則表達式拆分項目,然后將結果放入字典中。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;



namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string pattern = "(?'name'[^:]):(?'value'.*)";
            string input = "user:jim;id:23;group:49st";
            Dictionary<string,string> dict = input.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => new
            {
                name = Regex.Match(x, pattern).Groups["name"].Value,
                value = Regex.Match(x, pattern).Groups["value"].Value
            }).GroupBy(x => x.name, y => y.value)
            .ToDictionary(x => x.Key, y => y.FirstOrDefault());

            dict["group"] = "76pm";

            string output = string.Join(";",dict.AsEnumerable().Select(x => string.Join(":", new string[] {x.Key, x.Value})).ToArray());

        }
    }
}

那只是做到這一點的一種方法。 希望對您有幫助。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace stringi
{
    class Program
    {
        static void Main(string[] args)
        {
            //this is your original string
            string s = "user:jim;id:23;group:49st";
            //string with replace characters
            string s2 = "76pm";

            //convert string to char array so you can rewrite character
            char[] c = s.ToCharArray(0, s.Length);

            //asign characters to right place
            c[21] = s2[0];
            c[22] = s2[1];
            c[23] = s2[2];
            c[24] = s2[3];

            //this is your new string
            string new_s = new string(c);

            //output your new string
            Console.WriteLine(new_s);

            Console.ReadLine();
        }
    }
}
string a = "user:jim;id:23;group:49st";

string b = a.Replace("49st", "76pm");

Console.Write(b);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM