-1

I am using C#

I got a string which looks something like this :

myString = "User1:John&User2:Bob'More text"

I used

var parsed = HttpUtility.ParseQueryString(myString);

and then i use parsed["User1"] and parsed["User2"] to get the data.

My problem is that parsed["User2"] returns me not only the name but also everything that comes after it.

I thought maybe to then seperate by the char '
But i not sure how to do it since it has a specific behaviour in Visual studio.

I thought about something like this?

private static string seperateStringByChar(string text)
{
    int indexOfChar = text.IndexOf(');
    if (indexOfChar > 0)
    {
        return text.Substring(0, indexOfChar);
    }
    else
    {
        return "";
    }
}
kresa
  • 135
  • 2
  • 3
  • 13
  • And what was the problem about your attempt? How did you use the return of that method? – t.m. Dec 28 '16 at 09:56
  • And? did the thing you though work? – Jeroen van Langen Dec 28 '16 at 09:56
  • Use `if (s.IndexOf("'") > -1) { return text.Substring(0, text.IndexOf("'")); } else { return string.Empty; }` – Wiktor Stribiżew Dec 28 '16 at 09:57
  • regex might be more useful as User2:Bob*'More text"* would be treated as a User2 value if you using ParseQueryString – Vladimir Dec 28 '16 at 09:57
  • My problem is that i cant use ' Is there a way to decorate it somehow to be able to use it? Since visual studio uses it for writting text inside so i cant put it inside a function the way i do. – kresa Dec 28 '16 at 09:58
  • Why use a method to parse a string that is not in the correct format for that method? The separator is the = char not the colon : – Steve Dec 28 '16 at 09:58
  • You should put a backslash ( \ ) before it. As it is the escape character https://msdn.microsoft.com/en-us/library/h21280bw.aspx – t.m. Dec 28 '16 at 09:59

2 Answers2

0

A clean way of doing it is by splitting the string besides the index of the ' and then getting the substring.

var splittedText = text.Split('\'');

Then you can separate it further. e.g

var splittedText2 = splittedtText[0].Split('\&');
var User1 = splittedText2[0].Split(':')[1];
var User2 = splittedText2[1].Split(':')[1];

Let's sum up the splitting.

var users=myString.Split('\'');
var john = users.Split('&')[0].Split(':')[1];
var bob = users.Split('&')[1].Split(':')[1];
Jamshaid K.
  • 3,555
  • 1
  • 27
  • 42
0

This worked for me as Wiktor suggested.

if (s.IndexOf("'") > -1) { return text.Substring(0, text.IndexOf("'")); } else { return string.Empty; }

kresa
  • 135
  • 2
  • 3
  • 13