1

if I have a string along the lines of: "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;"

sorry if the question is easy but I haven't found a specific answer, just cases different than mine.

5
  • 1
    Split the string on ';'. Then split each string on ':'. Replace where the first string part is 'group'. Finally rebuild your string. Commented Apr 5, 2016 at 11:21
  • 1
    Do you want to change 49st to 76pm or group:x to group:76pm ? Commented Apr 5, 2016 at 11:21
  • just want to replace the two. well, the variable that is in those places, so yes, group: x to group:y Commented Apr 5, 2016 at 11:21
  • @stuartd that wont work, if it's a dynamically crafted string. Carra has given the appropriate solution. Commented Apr 5, 2016 at 11:24
  • since the groups change, I can't do it manually, "49st", "76pm". No, that 23 thing was just a mistake Commented Apr 5, 2016 at 11:24

6 Answers 6

7

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 is essentially an if but it is put onto one line using a ternary operator.

Alternatively, if you know what text is there already and what it should be replaced with, you can just use a 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

if(s.Contains("group:"))
{
    //Code
}
Sign up to request clarification or add additional context in comments.

4 Comments

This assumes that "group" is the last name-value pair. What if the string was "group:49st;user:jim;id:23;"?
Quick and easy. Thank you!
@razzv If this worked for you it would be good to mark it as the answer :)
Did it just now, wasn't aware of that. Thanks again!:)
3

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

1 Comment

Thanks. I really appreciate your comment :)
1

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

Comments

1

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

        }
    }
}

Comments

1

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

Comments

0
string a = "user:jim;id:23;group:49st";

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

Console.Write(b);

4 Comments

The OP clarified that they want to replace whatever comes after "group" with a new value, not just the specific case shown in the example.
Then it should be easy to figure out: string b = a.Replace("group:49st", "group:76pm");
@Gustav No, because the idea is that you don't know what comes after "group".
@Gustav Dynamic strings? The OP may not know what's coming in.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.