Replace value from a variable to another value - c#

i have a controller where i read a html file into a variable.
After read it i replace some values from the variable to other values,
but the problem is that nothing happend.
What is wrong here ?
can someone give me a hand with this?
string path = "/mypath/myfile.html";
string s = System.IO.File.ReadAllText(path);
s.Replace("#%a%#","hi");
s.Replace("#%b%#","yo");
s.Replace("#%c%#","asdfasdf");
s.Replace("#%d%#", "http://www.google.com");

Strings are immutable - you should assign result of replacement to your string. Also you can chain replacement operations like this:
string s = System.IO.File.ReadAllText(path)
.Replace("#%a%#","hi")
.Replace("#%b%#","yo")
.Replace("#%c%#","asdfasdf")
.Replace("#%d%#", "http://www.google.com");
Just keep in mind - all string operations (like Replace, Substring etc) will create and return new string, instead of changing original. Same implies to operations on DateTime and other immutable objects.
UPDATE: You can also declare dictionary of your replacements and update string in a loop:
var replacements = new Dictionary<string, string> {
{ "#%a%#","hi" }, { "#%b%#","yo" }, { "#%c%#","asdfasdf" } // ...
};
string s = System.IO.File.ReadAllText(path);
foreach(var replacement in replacements)
s = s.Replace(replacement.Key, repalcement.Value);

A string is immutable. Basically, an object is immutable if its state doesn’t change once the object has been created. Consequently, a class is immutable if its instances are immutable.
string path = "/mypath/myfile.html";
string s = System.IO.File.ReadAllText(path);
s = s.Replace("#%a%#","hi");
s = s.Replace("#%b%#","yo");
s = s.Replace("#%c%#","asdfasdf");
s = s.Replace("#%d%#", "http://www.google.com");

Related

Deleted words from a string

Is there any possibility to delete specific words from a string? For exempla
string x ="documents\bin\debug" and I want to delete "\bin\debug".
Use String.Replace():
string x = #"documents\bin\debug";
string desiredString = x.Replace(#"\bin\debug", String.Empty);
Note: The key thing here is that you have to assign the string returned by the Replace() function to a variable. (From your comment on the question, it is the problem). This can either be another variable (as in the above example) or the same variable:
string x = x.Replace(#"\bin\debug", String.Empty);
Implicitly, not assigning the return value to a variable (or using the former way) will keep the value of x, unchanged, which is the exact problem you're facing. Hope it helps :)
Use string replace
string x = #"documents\bin\debug";
string nestring = x.Replace(#"\bin\debug", "");
Console.WriteLine(nestring);

Are there methods to convert between any string and a valid variable name in c#

I need such methods to save some information (for example, formulas) in a variable name.
Of course, it is easy to convert any string to a valid name. But I have 2 unique requirements:
1.The conversion can happen in both directions and after 2 times conversion, we should get the same original string.
Say, convert2OriginalString(Convert2Variable(originalstring)) should always equal to originalstring.
The generated variable name should be readable, not just ugly numbers.
Thank you in advance,
Just about the only "special" character that is allowed for variable names is the underscore "_"
You could create a custom Dictionary with all of the characters you want to escape, and then iterate through it replacing "special" characters in your string with escaped characters:
private static string ConvertToSafeName(string input)
{
var output = input;
foreach (var lookup in GetLookups())
{
output = output.Replace(lookup.Key, lookup.Value);
}
return output;
}
private static string RevertToSpecialName(string input)
{
var output = input;
foreach (var lookup in GetLookups())
{
output = output.Replace(lookup.Value, lookup.Key);
}
return output;
}
private static Dictionary<string, string> GetLookups()
{
Dictionary<string, string> lookups = new Dictionary<string, string>();
lookups.Add("=", "_eq_");
lookups.Add(">", "_gt_");
lookups.Add("-", "_mn_");
lookups.Add(" ", "__"); // double underscore for space
return lookups;
}
It's not 100% foolproof, but "x=y-z" translates to "x_eq_y_mn_z" and converts back again, and is fairly human readable

Convert String Into Dynamic Object

Is there a straightforward way of converting:
string str = "a=1,b=2,c=3";
into:
dynamic d = new { a = 1, b = 2, c = 3 };
I think I could probably write a function that splits the string and loops the results to create the dynamic object. I was just wondering if there was a more elegant way of doing this.
I think if you convert the "=" into ":" and wrap everything with curly brackets you'll get a valid JSON string.
You can then use JSON.NET to deserialize it into a dynamic object:
dynamic d = JsonConvert.DeserializeObject<dynamic>(jsonString);
You'll get what you want.
You may use Microsoft Roslyn (here's the all-in-one NuGet package):
class Program
{
static void Main(string[] args)
{
string str = "a=1,b=2,c=3,d=\"4=four\"";
string script = String.Format("new {{ {0} }}",str);
var engine = new ScriptEngine();
dynamic d = engine.CreateSession().Execute(script);
}
}
And if you want to add even more complex types:
string str = "a=1,b=2,c=3,d=\"4=four\",e=Guid.NewGuid()";
...
engine.AddReference(typeof(System.Guid).Assembly);
engine.ImportNamespace("System");
...
dynamic d = engine.CreateSession().Execute(script);
Based on the question in your comment, there are code injection vulnerabilities. Add the System reference and namespace as shown right above, then replace the str with:
string str =
#" a=1, oops = (new Func<int>(() => {
Console.WriteLine(
""Security incident!!! User {0}\\{1} exposed "",
Environment.UserDomainName,
Environment.UserName);
return 1;
})).Invoke() ";
The question you described is something like deserialization, that is, contructing objects from data form(like string, byte array, stream, etc). Hope this link helps: http://msdn.microsoft.com/en-us/library/vstudio/ms233843.aspx
Here's a solution using ExpandoObject to store it after parsing it yourself. Right now it adds all values as strings, but you could add some parsing to try to turn it into a double, int, or long (you'd probably want to try it in that order).
static dynamic Parse(string str)
{
IDictionary<String, Object> obj = new ExpandoObject();
foreach (var assignment in str.Split(','))
{
var sections = assignment.Split('=');
obj.Add(sections[0], sections[1]);
}
return obj;
}
Use it like:
dynamic d = Parse("a=1,b=2,c=3");
// d.a is "1"

Returning a new value

I have write a function but this function still returns me the old string in stead of the new one. I don't know how to return a new string when you did something with the old one
By example:
public string TestCode(string testString)
{
// Here something happens with the testString
//return testString; <-- i am returning still the same how can i return the new string //where something is happened with in the function above
}
// Here something happens with the testString
Make sure what ever you are doing with the string, you are assigning it back to testString like.
testString = testString.Replace("A","B");
since string are immutable.
I assume you are calling the function like:
string somestring = "ABC";
somestring = TestCode(somestring);
Simply make sure you assign the new string value to a variable (or the parameter testString). For example, a very common mistake here is:
testString.Replace("a", ""); // remove the "a"s
This should be:
return testString.Replace("a", ""); // remove the "a"s
or
testString = testString.Replace("a", ""); // remove the "a"s
...
return testString;
The point is: string is immutable: Replace etc do not change the old string: they create a new one that you need to store somewhere.
String is immutable (i.e. cant be changed). You have to do like this
myString = TestCode(myString)

Loop Problem: Assign data to different strings when in a loop

I have a string which consists of different fields. So what I want to do is get the different text and assign each of them into a field.
ex: Hello Allan IBM
so what I want to do is:
put these three words in different strings like
string Greeting = "Hello"
string Name = "Allan"
string Company = "IBM"
//all of it happening in a loop.
string data = "Hello Allan IBM"
string s = data[i].ToString();
string[] words = s.Split(',');
foreach (string word in words) {
Console.WriteLine(word);
}
any suggestions?
thanks hope to hear from you soon
If I understand correctly you have a string with place-holders and you want to put different string in those place-holders:
var format="{0}, {1} {2}. How are you?";
//string Greeting = "Hello"
//string Name = "Allan"
//string Company = "IBM"
//all of it happening in a loop.
string data = ...; //I think you have an array of strings separated by ,
foreach( va s in data){
{
//string s = data[i];//.ToString(); - it is already a string array
string[] words = data[i].Split(',');
Console.WriteLine(format, words[0], words[1], words[2]);
}
To me it sound not like a problem that can be solved with a loop. The essential problem is that the loop can only work if you do exactly the same operation on the items within the loop. If your problem doesn't fit, you end up with a dozen of lines of code within the loop to handle special cases, what could have been written in a shorter way without a loop.
If there are only two or three strings you have to set (what should be the case if you have named variables), assign them from the indexes of the split string. An alternative would be using regular expressions to match some patterns to make it more robust, if one of the expected strings is missing.
Another possibility would be to set attributes on members or properties like:
[MyParseAttribute(/*position*/ /*regex*/)]
string Greeting {get;set;}
And use reflexion to populate them. Here you could create a loop on all properties having that attribute, as it sounds to me that you are eager to create a loop :-)

Categories

Resources