简体   繁体   English

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

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

if I have a string along the lines of: "user:jim;id:23;group:49st;" 如果我有以下字符串:“ user:jim; id:23; group:49st;” how can I replace the group code (49st) with something else, so that it shows: "user:jim;id=23;group:76pm;" 我如何用其他内容替换组代码(49st),以便显示:“ user:jim; id = 23; group:76pm;”

sorry if the question is easy but I haven't found a specific answer, just cases different than mine. 抱歉,如果问题很简单,但我没有找到具体答案,只是与我的情况不同。

You can use the index of "group" like this 您可以像这样使用“组”的索引

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;

The line with the s = criteria ? true : false 符合s = criteria ? true : false s = criteria ? true : false is essentially an if but it is put onto one line using a ternary operator. s = criteria ? true : false本质上是一个if,但是使用三元运算符将其放在一行上。

Alternatively, if you know what text is there already and what it should be replaced with, you can just use a Replace 另外,如果您知道已经有哪些文本以及应将其替换为哪种文本,则可以使用“ Replace

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

As an added precaution, if you are not always going to have this "group:" part in the string, to avoid errors put this inside an if which checks first 作为附加的预防措施,如果您并非总是要在字符串中包含此“ group:”部分,为避免错误,请将其放在if首先检查的if

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

Find the match using regex and replace it with new value in original string as mentioned below: 使用正则表达式查找匹配项,并将其替换为原始字符串中的新值,如下所述:

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

This solution should work no matter where the group appears in the string: 无论组在字符串中的何处出现,此解决方案都应该起作用:

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

Here is a very generic method for splitting your input, changing items, then rejoining items to a string. 这是一种非常通用的方法,用于拆分输入,更改项目,然后将项目重新连接到字符串。 It is not meant for single replacement in your example, but is meant to show how to split and join items in string. 在您的示例中,它并不是要进行单个替换,而是要显示如何拆分和合并字符串中的项目。

I used Regex to split the items and then put results into a dictionary. 我使用正则表达式拆分项目,然后将结果放入字典中。

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());

        }
    }
}

That is just one way to do it. 那只是做到这一点的一种方法。 I hope it will help you. 希望对您有帮助。

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