string.replace not working for me - c#

I have this code:
string encodedKeywordsQueryValue = HttpUtility.UrlEncode(HttpContext.Current.Request.QueryString["keywords"]);
query = query.Replace(HttpContext.Current.Request.QueryString["keywords"], encodedKeywordsQueryValue);
where
HttpContext.Current.Request.QueryString["keywords"] = "abc& abc"
and
encodedKeywordsQueryValue=abc%26+abc
My old string value is not getting replaced with new one.
Can anyone suggest me to do this? I have tried combination of remove and insert methods of string but not getting desired results.
Kindly help me with this.

HttpContext.Current.Request.QueryString["keywords"]="abc& abc" and
encodedKeywordsQueryValue=abc%26+abc
reading the documentation of replace method would tell you that it does not know about URL encoding and does not care - it is a string method. So, work on unencoded strings. There is no like style behavior - it is an exact "match and replace".
I would suggest you make a unit test for this behavior and then work out how you would like it to be - then you could for example also make a post here that is somehow baseline useful because it would have an exact example of which behavior does not work, not some riddle for us to solve.

you should have an exact string on the left side of replace. it doesn't act like 'LIKE'. see the example below:
string str1 = "abc";
string str2 = "abc&def";
str2.replace("d", str1);
result will be:
abc&abcef
hope it helps

Related

Nested string interpolation

I've faced an issue with nested string interpolation in C# 6.
For example, there is a string:
string test = "StartText MiddleText1 MiddleText2 EndText";
If I want to apply ToUpper() method for MiddleText1 only, I can do this way:
string test = $#"StartText {"MiddleText1".ToUpper()} MiddleText2 EndText";
But what if I want to apply a string method, for example Replace() for this part of string:
{"Middletext1".ToUpper()} MiddleText2
I expected that something like this will work:
string test = $#"StartText {"{"MiddleText1".ToUpper()} MiddleText2".Replace("x", "y")} EndText";
But this syntax is wrong - I've tried a lot variations, played with quotas but I couldn't get correct syntax for this purpose.
I'd wish to not split the string in a different parts. Is there a way to solve it using interpolation feature only?
Stop trying to do everything in one line is my suggestion
The following is the answer
var middle = "MiddleText1";
middle = middle.ToUpper();
var middle2 = $"{middle} MiddleText2";
middle2 = middle2.Replace("x", "y");
string test = $"StartText {middle2} EndText";
Which, when you add it all together.
string test = $"StartText {$"{"MiddleText1".ToUpper()} MiddleText2".Replace("x", "y")} EndText";
In short, you were just missing a $
However, Even this is messy as i am not sure what all the replaces are for, where this text comes from, and what the issue is you are trying to solve

Split string at semicolon get second part only

I have a string in the following format:
message:action
How can I parse this string and get the second part only?
The action might be different the first part will always be the same: message:
Is this a correct way?
string value="message:action";
string[] result = value.Split(':');
string action = result[1];
Yes it is. Or, since the first part is always the same, you could simply use substring:
value.SubString(8);
That solution is fine, but it's a little more work than necessary. If you know that the string will always start with "message:", why not just do this:
var action = value.Substring(8);
However, if the string that comes before the : might change, but you still only care about what comes after it, you could do this:
var action = value.Substring(value.IndexOf(':') + 1);
Yes, your solution will work. However, if the first part is always the same, another possibility is to use Substring as pswg's answer mentions.
If you know that the string will start with message: you can do this:
String value="message:action";
String result = value.Replace("message:","");
It's OK, although if you worry about there being colons in the content (e.g., "message:action:do this"):
string value="message:action";
string[] result = value.Split(':');
string action = value.Substring(result[0].Length);
(this is of course if it's not always starting with "message:")
If you want to have self-documenting code, you can use regex (so you don't think in the future, what the heck is this code and why do I take second part).
string value = "message:action";
string action = Regex.Match(value, "(?<=^message:).*").Value; // will throw exception in case if someday format changes
I'm adding one more answer for legibility. There are several correct answers in the thread so far.
Just to offer a very readable alternative at very little cost of performance consider the following:
string value = "message:action";
string action = value.Split(':').Skip(1);

How do I do multiple replaces on a string at the same time?

string rawConnString = Properties.Settings.Default.ConnectionString;
I want to do this with "rawConnString":
rawConnString.Replace("<<DATA_SOURCE>>", server);
rawConnString.Replace("<<INITIAL_CATALOG>>", "tempdb");
Then set the final string to variable finalConnString.
How would I go about doing this?
This is ASP .NET 4.0/C# btw.
string finalString = Properties.Settings.Default.ConnectionString.Replace("<<DATA_SOURCE>>", server).Replace("<<INITIAL_CATALOG>>", "tempdb");
will do it all in one line of code. But it's uglier IMO because you'll have to scroll. The code in your question seems a LOT cleaner and more readable to me.
And doing it in one line of code won't help your performance at all. It should all compile down to the same MSIL either way. I'd leave it as you had it.
Not sure if this is what you're after, but you can chain them:
var finalConnString = rawConnString.Replace("<<DATA_SOURCE>>", server)
.Replace("<<INITIAL_CATALOG>>", "tempdb");
If you're looking to do it with a single method call, I don't think there's anything native to .NET. You can always create an extension method though. Here's a performance-conscious ReplaceMany implementation (signature .ReplaceMany(string[] oldValues, string[] newValues)).
This is frankly trivial; you have 90% of the code you need:
string rawConnString = Properties.Settings.Default.ConnectionString;
string finalConnString = rawConnString
.Replace("<<DATA_SOURCE>>", server)
.Replace("<<INITIAL_CATALOG>>", "tempdb");
To avoid using two back-to-back calls of Replace, you can use regular expressions. However, this is far less readable than the original:
string connString = Regex.Replace(
rawConnString
, "(<<DATA_SOURCE>>)|(<<INITIAL_CATALOG>>)"
, m => m.Groups[1].Success ? server : "tempdb"
);
Link to ideone.
you mean something like this
string tempString=rawConnString.Replace("<<DATA_SOURCE>>", server);
sting finalstring=tempString.Replace("<<INITIAL_CATALOG>>", "tempdb");
First, String.replace does not change the original string: it creates a new string. So you have to assign the return value to something. So the logically simplest thing to do is:
finalstring=rawConnString.Replace("<<DATA_SOURCE>>", server);
finalstring=finalstring.Replace("<<INITIAL_CATALOG>>", "tempdb");
Note that for the second replace, you want to start with the results of the first replace, not the original string.
As String.replace returns a string, and String.replace takes a string, you might find it easier to run them together:
finalstring=rawConnString.Replace("<<DATA_SOURCE>>", server).Replace("<<INITIAL_CATALOG>>", "tempdb");

How to remove a part of the string

I am wondering How i can remove a part if my string .
For example my string will be :
string test = "/blabla/test/ok";
How can I say that I want to remove /blabla/ ?
And my string will be /test/ok.
test = test.Replace("/blabla/", string.Empty);
Or
test = test.Substring("/blabla/".Length - 1);
You really should take a look at the documentation of the String class and all the different methods and properties it holds.
How about stripping the first 8 characters?
test = test.Substring(7);
test = test.Replace("/blabla", "");
You could simply .Replace() it:
test.Replace("/blabla/",""); //Yields /test/ok
If you what to do it in more general case you'll need regular expressions here:
Regex.Replace(#"/blabla/test/ok", #"^//(.*?)//(.*?)//(.*?)$", #"/$2/$3")
It depends on whether you're going to be snipping out the same bit of text every single time or whether the text you're removing can differ.
If you know it's a particular block of text which will only appear once in the string then use Curt's answer (test = test.replace("/blabla", "");).
If it's anything else then, personally, I'd use a variant of Arcturus's answer to snip out the unwanted segment of the string (test = test.Substring(7);).
That's my two cents anyway.

how to get a String with String.Format to execute?

I have a little chunk of code (see below) that is returning the string:
string.Format("{0}----{1}",3,"test 2");
so how do I get this to actually "Execute"? To run and do the format/replacement of {0} and {1}?
My Code snippet:
StringBuilder sb = new StringBuilder();
sb.Append("{0}----{1}\",");
sb.AppendFormat(ReturnParamValue(siDTO, "siDTO.SuggestionItemID,siDTO.Title"));
string sbStr = "=string.Format(\""+sb.ToString()+");";
yes, ReturnParamValue gives the actually value of the DTO.
Anyways, I've taken a look at the following (but it doesn't say how to execute it:
How to get String.Format not to parse {0}
Maybe, I just should put my code snippet in a method. But, what then?
Why are you including String.Format in the string itself?
If you're looking for a generic "let me evaluate this arbitrary expression I've built up in a string" then there isn't a simple answer.
If, instead, you're looking at how to provide the parameters to the string from a function call, then you've got yourself all twisted up and working too hard.
Try something like this, based on your original code:
string result
= string.Format(
"{0}----{1}",
ReturnParamValue(siDTO, "siDTO.SuggestionItemID,siDTO.Title"));
Though, this won't entirely work since your original code seems to be only providing a single value, and you have two values in your format string - the {0} will be replaced with the value from your function, and {1} left unchanged.
What output are you expecting?
Does your ReturnParamValue() function try to return both the label and the value in a single string? If it does, and if they're comma separated, then you could try this:
var value = ReturnParamValue(siDTO, "siDTO.SuggestionItemID,siDTO.Title"));
var pieces = string.Split(',');
string result
= string.Format( "{0}----{1}", pieces[0], pieces[1]);
Though this is seriously working too hard if ReturnParamValue() is a method you control.
Update Fri 6 August
Check out the declaration for string.Format() as shown on MSDN:
public static string Format(
string format,
params Object[] args
)
Unlike the special casing you might have seen in C for printf(), there's nothing special or unusual about the way string.Format() handles multiple parameters. The key is the params keyword, which asks the compiler to provide a little "syntactic sugar" where it combines the parameters into an array for you.
Key here is that the wrapping doesn't happen if you're already passing a single object[] - so if you wanted to, you could do something like this:
object[] parameters
= ReturnParamValues(siDTO, "siDTO.SuggestionItemID,siDTO.Title");
string result
= string.Format("{0}----{1}----{2}", parameters);
Though, if I saw something like this in any codebase I maintained, I'd be treating it as a code-smell and looking for a better way to solve the problem.
Just because it's possible doesn't mean it's advisable. YMMV, of course.
I don't think you can execute it. Java is not really a interpreted language.
You may make use of scripting languages (which can even embed in your Java app as I know, start from JDK6) for such purpose, like Groovy
You could use RegEx to parse the three parameters out of the string, and then pass them to a real, actual string.Format method :-)
It looks like what you want is something like this:
string sbStr = string.Format("{0}----{1}", siDTO.SuggestionItemID, siDTO.Title);
Maybe i didn't understand your question completely, but it sounds like you need to format a format-string. If that's true you could maybe try something like this:
int width = 5;
string format = String.Format("{{0,{0}}}----{{1,{0}}}", width);
string result = String.Format(format, "ab", "cd");
So the trick is simply to escape the { or } by using a double {{ or }}.

Categories

Resources