I am adding a string (a) to another string (b) before I store it in DB, when I retrieve the value from DB, I want to remove the string(b) from string (a). string (b) is a constant. How can I do it
string a= "text1";
string b="text2";
string c = a+b;
I want to remove b from c after I retrive it from db
c = c.Replace(b, "");
Would be a simple way to do so.
Rather than do any of that, create a computed column in the DB that has the extra text.
Less storage; less code.
Try String.Replace - MSDN documentation here.
As #SvenS has pointed in #Khaled Nassar answer, using String.Replace won't work "as is" in your situation.
One acceptable solution may #Mitch's one, but if you don't have that access to modify your database, maybe there's another solution in pure C#:
int indexOfB = c.LastIndexOf(b);
string cWithoutB = c;
if(indexOfB >= 0)
{
c.Substring(0, indexOfB);
}
This prevents replacing more than once the same string as b, because who knows if some user save the same text as b and logic shouldn't be removing it if it's not the one predefined by your application.
Related
I have a string like
string variable1="EXAMPLE";
and later somewhere in my code, I use like
Console.WriteLine(variable1.ToLower());
I may use variable1.ToLower() multiple times. But now I want to store the variablename that is converted to Lower in a separate new variable, that is, I have to extract variable1 from Console.WriteLine(variable1.ToLower()); line and store it in a string variable. Is that possible?
My main goal is that, If my code has variable1.ToLower() in too many places, then I have to run an application, that replaces all variable1.ToLower() to a new string that has the value of variable1.ToLower(). Please Note that using too many variable1.ToLower() in a code is a violation.So I am just creating a new variable to store the value of variable1.ToLower() and use that new variable instead of variable1.ToLower() in every place.
Assuming I understand the question, why not just do this?
var lower = variable1.ToLower();
Console.WriteLine(lower);
String.ToLower creates a copy of the original string. So the original string is not modified and you can safely use it otherwise.
string variable1 = "EXAMPLE";
string lowerCaseVariable1 = variable1.ToLower();
Console.WriteLine($"Is still the original string: {variable1}");
Console.WriteLine($"Is the lower case copy of the original string: {lowerCaseVariable1}");
EDIT:
If you want to get the name of the string variable instead of the content, you can use nameof (Link).
string variable1 = "EXAMPLE";
string nameOfVariable1 = nameof(variable1);
Console.WriteLine(variable1.ToLower());
Do you know another more proper way to do the same things ?
string initialTemplate = "{0}-{1}";
string template = string.Format(initialTemplate, "first", "{0}");
string answer = string.Format(template, "second");
Also the following way has actually known, but in my current case unfortunatelyI can't use that method(i think that that way more proper and the logic more clear):
string initialTemplate = "{0}-{{0}}";
string template = string.Format(initialTemplate, "first");
string answer = string.Format(template, "second");
Maybe is there another hint how to do that?
UPDATE
I'm so sorry but from yours answers I've learnt that my question wasn't enough clear. So I've added a little bit more description.
My situation:
//that template is actually placed in *.resx file
//I want storing only one template and use that in different situations
public const string InitialTemplate = "{0}-{1}";
public static string GetMessage(string one, string two)
{
return string.Format(InitialTemplate, one, two);
}
public static string GetTemplate(string one)
{
return string.Format(InitialTemplate, one, "{0}");
}
//or morew universal way
public static string GetTemplate(params object[] args)
{
return string.Format(InitialTemplate, args, "{0}");
}
static void Main(string[] args)
{
//in almost all cases in my project i need to use string.format like this
string message = GetMessage("one", "two");
//but there is another way where i have to use
//the template have already been assigned first argument
//the result must be "one-{0}"
string getTemplateWithAssignedFirstArg = GetTemplate("one");
}
Do you know more proper way for that kind of situation ?
If you are using C# 6 you can also use string interpolation.
https://msdn.microsoft.com/en-us/library/dn961160.aspx
var answer = $"{firstVar}-{secondVar}";
string initialTemplate = "{0}-{1}";
string answer = string.Format(initialTemplate, "first", "second");
Should do the trick. Or cut out the middle man with:
string answer = string.Format("{0}-{1}", "first", "second");
String.Format is a very useful convenience, but I'd be wary of using it to build format strings that you're going to use to create other format strings. Someone trying to maintain that code, figure out what's going on, and perhaps modify it will be baffled. Using String.Format that way is technically possible, and there could even be scenarios where it's useful, but it's probably just going to result in something that works but is very difficult to understand and debug.
My first suggestion would be to use a StringBuilder. Even when you're appending to the StringBuilder you can use String.Format if needed to create the individual strings.
I wonder if perhaps what you describe in the question is taking place across multiple methods (which is why you might be building your format string in steps.) If that's the case, I recommend not building the string in steps like that. Don't actually start building the string until you have all of the data that you need together, and then build the string at once.
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);
I m looking for a way to convert a string to a unique Id.
Ideas invited for an algorithm that comes up with a unique number for each string sent to it.
I tried to use hash code but then realized that two strings could have the same hash code.
How do I generate a unique code for each string as input and two same strings should generate me the same id at all times.
Can you have characters in your "unique ID"? If so, this should work ;-)
public string MakeUnique(string s)
{
return s;
}
All ID's will be unique to the value provided. The same string, will produce the exact same ID. That's what you wanted right?
If it's an integer result you want, how about converting each character to an int...
public int MakeUnique(string s)
{
string result = "";
foreach(var c in s)
{
result += ((int)c).ToString();
}
return Int.Parse(result);
}
WARNING: This will break if the string is too big
Simply append or prepend a guid:
string foo = "MyString";
//Simply throw it on the end
string uniqueString = foo + Guid.NewGuid();
//Prepend with underscore
string uniqueString = String.Format("{0}_{1}", foo, Guid.NewGuid());
//Append with underscore
string uniqueString = String.Format("{0}_{1}", Guid.NewGuid(), foo);
Edit (new requirement)
You have not provided enough information for me to post a great answer to this question. For example, environment (web, winforms, etc.) would be beneficial.
To point you in the right direction...
If the unique string that is returned needs to be the same when you pass in a string a second time, you could maintain a history of generated strings and check it each time generation is requested.
Truthfully, there are lots of ways to skin this cat...
If the original string is sensitive, similar to Gravatar, you could encrypt the string with MD5 encryption
As you have stated, and #Austin Salonen commented, they're not 100% unique, but the risk is low:
How are hash functions like MD5 unique?
A string can be fairly long and consists of charactes, which are 16-bit values. The number of possible strings is huge (much more than the range of integer or Guid). So you can't have a function that "just" translates a string into some guaranteed unique code, without some help.
You could use a database table: lookup your string in the table. If it's not there, insert it, generating a new (sequential) unique id. If it's there, use that id. The number of possible strings is huge, the number of strings you encounter, probably not.
I have a coded string that I'd like to retrieve a value from. I realize that I can do some string manipulation (IndexOf, LastIndexOf, etc.) to pull out 12_35_55_219 from the below string but I was wondering if there was a cleaner way of doing so.
"AddedProject[12_35_55_219]0"
If you can be sure of the format of the string, then several possibilities exist:
My favorite is to create a very simple tokenizer:
string[] arrParts = yourString.Split( "[]".ToCharArray() );
Since there is a regular format to the string, arrParts will have three entries, and the part you're interested in would be arrParts[1].
If the string format varies, then you will have to use other techniques.
So in summary, if you have a pattern that you can apply to your string, the easiest is to use regular expressions, as per Guffa example.
On the other hand you have different tokens all the time to define the start and end of your string, then you should use the IndexOf and LastIndexOf combination and pass the tokens as a parameter, making the example from Fredrik a bit more generic:
string GetMiddleString(string input, string firsttoken, string lasttoken)
{
int pos1 = input.IndexOf(firsttoken) + 1;
int pos2 = input.IndexOf(lasttoken);
string result = input.Substring(pos1 , pos2 - pos1);
return result
}
And this is assuming that your tokens only happens one time in the string.
That depends on how much the string can vary. You can for example use a regular expression:
string input = "AddedProject[12_35_55_219]0";
string part = Regex.Match(input, #"\[[\d_]+\]").Captures[0].Value;
There are two methods which you may find useful, there is IndexOf and LastIndexOf with the square brackets as your parameters. With a little bit of research, you should be able to pull out the project number.
Here is a improvement from Wagner Silveira's GetMiddleString
string GetMiddleString(string input, string firsttoken, string lasttoken)
{
int pos1 = input.ToLower().IndexOf(firsttoken.ToLower()) + firsttoken.Length;
int pos2 = input.ToLower().IndexOf(lasttoken.ToLower());
return input.Substring(pos1 , pos2 - pos1);
}
And here how you use it
string data = "AddedProject[12_35_55_219]0";
string[] split = data.Split("[]".ToCharArray());
rtbHelp.Text += GetMiddleString(data, split[0], split[2]).Trim("[]".ToCharArray());//print it to my C# winForm RichTextBox Help