I would like to find match
I prefer to "IndexOf" (not RegExp or something, becuase it is pretty simple codes).
I have a problem with strange character.
The situation is Given, I can not control it.
Let's see the screenshot, that is good enough.
It should make result "-1" but it makes not "-1" (0 in this case).
Thanks.
string myString1 = "abc";
string myString2 = "abc�";
MessageBox.Show(
"Result \n" +
myString1.IndexOf(myString2));
enter image description here
You should be using StringComparison.Ordinal
string myString1 = "abc";
string myString2 = "abc�";
MessageBox.Show("Result \n" + myString1.IndexOf(myString2, StringComparison.Ordinal));
It's just on of those weird "gotchas" that shows using culture information can sometimes really matter.
Related
I have 3 booleans:
Boat, Plane, Car
And 3 strings:
ReloadBoat, ReloadPlane, ReloadCar
Depending on these booleans, if false, I need to add commas between the strings.
string errorMessage = (Boat? "" : " " + ReloadBoat) + (Plane? "" : (errMessage) + ReloadPlane) + (Car? "" : ", " + ReloadCar);
For the above, the issue I am getting is, if both Boat and Plane are true, I am getting the errorMessage as ", ReloadCar".
I want it to be "ReloadCar" only.
Any idea on how to do this?
Breaking it out makes the code more readable and maintainable. It'll get really hard work to use your bools in the manner you have there. Instead I recommend you put the commas on your error messages as a matter of routine. Concatenate them together and remove any trailing commas:
string err="";
if(boatNeedsReload)
err+="ReloadBoatErrorMessageWithComma, ";
if(planeNeedsReload)
err+="ReloadPlaneErrorMessageWithComma, ";
if(carNeedsReload)
err+="ReloadCarErrorMessageWithoutComma";
err = err.TrimEnd(new[]{' ',','});
So the method is:
Put punctuation between all your elements regardless
Trim off trailing redundant punctuation as the last operation
I didn't put any punctuation after ReloadCar because as the last item, it isn't strictly necessary. If this were extended in future to add another item at the end you'd have to remember to punctuate ReloadCar. You might thus wish to consider punctuating car right now and not have to remember to do it next time
If you use a stringbuilder you can interrogate the length and knock 2 off it if needs be:
StringBuilder err=new StringBuilder();
if(boat)
err.Append("ReloadBoat, ");
if(plane)
err.Append("ReloadPlane, ");
if(car)
err.Append("ReloadCar, ");
if(err.Length>0);
err.Length-=2;
this time I did punctuate reloadcar because this method wouldn't work properly without it
Don't try to do too much on one line in your code; you'll reach a point where it needs modifying in a months time and it'll take longer to work out how it works and how to extend it than just breaking it out to something readable and hence maintainable
As an example, this does the same as the first code block, but it's a bit "what the..?"
string err = (
(boatNeedsReload ? "ReloadBoatErrorMessageWithComma, ":"")+
(planeNeedsReload ? "ReloadPlaneErrorMessageWithComma, ":"")+
(carNeedsReload ? "ReloadCarErrorMessageWithoutComma":""))
.TrimEnd(new[]{' ',','});
Falco makes a good point, that you should strive to make your Boolean variables have a name that declares a truth, like "isTooYoung" or "boatNeedsReload". Make your Boolean have a positive spirit, as it starts to get confusing if you write if(boatDoesntNeedReload==false). Note also that classic advice is to not compare a Boolean with another Boolean to realise a Boolean, but consider that comparing with false can make code more readable than using ! to invert a truth
I would create a list of strings with errors and appended to it based on the bools and string join them with a comma or whatever you want.
var boatErrorMessage = "boatErrorMessage";
var planeErrorMessage = "planeErrorMessage ";
var carErrorMessage = "carErrorMessage";
var isBoat = true;
var isPlane = false;
var isCar = true;
var errorMessageList = new List<string>();
if (isBoat)
errorMessageList.Add(boatErrorMessage);
if (isPlane)
errorMessageList.Add(planeErrorMessage);
if (isCar)
errorMessageList.Add(carErrorMessage);
Console.WriteLine(string.Join(", ", errorMessageList));
Output: boatErrorMessage, carErrorMessage
I've something like below.
var amount = "$1,000.99";
var formattedamount = string.Format("{0}{1}{0}", "\"", amount);
How can I achieve same using String interpolation?
I tried like below
var formattedamount1 = $"\"{amount}\"";
Is there any better way of doing this using string interpolation?
Update
Is there any better way of doing this using string interpolation
No, this is just string interpolation, you cant make the following any shorter and more readable really
var formattedamount1 = $"\"{amount}\"";
Original answer
$ - string interpolation (C# Reference)
To include a brace, "{" or "}", in the text produced by an
interpolated string, use two braces, "{{" or "}}". For more
information, see Escaping Braces.
Quotes are just escaped as normal
Example
string name = "Horace";
int age = 34;
Console.WriteLine($"He asked, \"Is your name {name}?\", but didn't wait for a reply :-{{");
Console.WriteLine($"{name} is {age} year{(age == 1 ? "" : "s")} old.");
Output
He asked, "Is your name Horace?", but didn't wait for a reply :-{
Horace is 34 years old.
Same thing you can achieve by doing:
var formattedamount1 = $"\"{amount}\"";
OR
var formattedamount1 = $#"""{amount}""";
It's basically allowing you to write string.Format(), but instead of using one string with "placeholders"({0}, {1}, .. {N}), you are directly writing/using your variable inside string.
Please read more about String Interpolation (DotNetPerls), $ - string interpolation to fully understand whats going on.
Just to give one more option, if you want to make sure you use the same quote at both the start and the end, you could use a separate variable for that:
string quote = "\"";
string amount = "$1,000.99";
string formattedAmount = $"{quote}{amount}{quote}";
I'm not sure I'd bother with that personally, but it's another option to consider.
I've been trying to make this URL a workable string in C#, but unfortunately using extra "" or "#" is not cutting it. Even breaking it into smaller strings is proving difficult. I want to be able to convert the entire address into a single string.
this is the full address:
<https://my.address.com/BOE/OpenDocument/opendoc/openDocument.jsp?iDocID=ATTPCi6c.mZInSt5o3t_Xr8&sIDType=CUID&&sInstance=Last&lsMZV_MAT="+URLEncode(""+[Material].[Material - Key])+"&lsIZV_MAT=>
I've also tried this:
string url = #"https://my.address.com/BOE/OpenDocument/opendoc/openDocument.jsp?iDocID=ATTPCi6c.mZInSt5o3t_Xr8&sIDType=CUID&&sInstance=Last&lsMZV_MAT=";
string url2 = #"+ URLEncode("" +[Material].[Material - Key]) + """"";
string url3 = #"&lsIZV_MAT=";
Any help is appreciated.
The simplest solution is put additional quotes inside string literal and use string.Concat to join all of them into single URL string:
string url = #"https://my.address.com/BOE/OpenDocument/opendoc/openDocument.jsp?iDocID=ATTPCi6c.mZInSt5o3t_Xr8&sIDType=CUID&&sInstance=Last&lsMZV_MAT=";
string url2 = #"""+URLEncode(""+[Material].[Material - Key])+""";
string url3 = #"&lsIZV_MAT=";
string resultUrl = string.Concat(url, url2, url3);
NB: You can use Equals method or == operator to check if the generated string matches with desired URL string.
This may be a bit of a workaround rather than an actual solution but if you load the string from a text file and run to a breakpoint after it you should be able to find the way the characters are store or just run it from that.
You may also have the issue of some of the spaces you've added being left over which StringName.Replace could solve if that's causing issues.
I'd recommend first checking what exactly is being produced after the third statement and then let us know so we can try and see the difference between the result and original.
You are missing the triple quotes at the beginning of url2
string url = #"https://my.address.com/BOE/OpenDocument/opendoc/openDocument.jsp?iDocID=ATTPCi6c.mZInSt5o3t_Xr8&sIDType=CUID&&sInstance=Last&lsMZV_MAT=";
string url2 = #"""+URLEncode(""+[Material].[Material - Key])+""";
string url3 = #"&lsIZV_MAT=";
I just made two updates
t&lsMZV_MAT=" to t&lsMZV_MAT="" AND
[Material - Key])+" to [Material - Key])+""
string s = #"<https://my.address.com/BOE/OpenDocument/opendoc/openDocument.jsp?iDocID=ATTPCi6c.mZInSt5o3t_Xr8&sIDType=CUID&&sInstance=Last&lsMZV_MAT=""+ URLEncode([Material].[Material - Key])+""&lsIZV_MAT=>";
Console.Write(s);
Console.ReadKey();
I have tried to do some research, but everything that I find does not cover what my current dilemma is.
String manipulation is basic right? But here is my problem, I am grabbing an email body from gmail, the body looks something like this (after removing all the HTML formatting, and is a constant string):
Name : Testy Von Test
Cell 1111111111
email testy#testy
Now I need to find the string "Name" and then use trimming to get the full name, but how do I distinguish between this? how do I tell my coding to look for everything from name until Cell and take everything from there? I really did try to find the solution as I believe I am just missing some logic in my mind. If you just give me a link to an article I will be happy to read up and apply the logic myself (I am not expecting anyone to do my work for me), I just need a proper nudge in the right direction please.
Thank you kindly in advance.
(as an edit if anyone should follow this question, look at all the answers, there are a bunch of amazing answers and ideas)
The string you have doesn't seem very well formatted. Name is followed by a colon, Cell is not... this could get very tricky...
but a simple solution using substring.
var s = "Name : Testy Von Test Cell 1111111111 email testy#testy";
var name = s.Substring(
s.IndexOf(":")+1,
s.IndexOf("Cell")-s.IndexOf(":")-1);
Is your mail body always in the exact format?
You can for instance do as shown in this jsfiddle.
var mailbody = 'Name : Testy Von Test Cell 1111111111 email testy#testy';
var nameregex = /Name(.+?)Cell/
var match = nameregex.exec(mailbody);
console.log(match[1]); // Outputs " : Testy Von Test "
In your example it would capture, as seen in the console input, " : Testy von test ". And you can then manipulate it however you'd like. You can also modify the regex with additional options, depending on how your mail outputs vary.
var mailbody = 'Name : Testy Von Test Cell 1111111111 email testy#testy';
var nameregex = /Name\s:\s(.+?)\sCell/
var match = nameregex.exec(mailbody);
console.log(match[1]); // Outputs "Testy Von Test"
What about this:
int start = myString.IndexOf("Name") + "Name : ".Length;
int len = myString.IndexOf("Cell") - start;
string res = myString.Substring(start, len);
Alternativly via Regex:
Regex r = new Regex("Name(.*)Cell");
string res = r.Matches[0].Value;
I have a string representation exactly like 'ComputerName -- IPAddress'; i.e:
'samarena -- 192.168.1.97'
. I want to get only the 'ComputerName' part from the actual representation by removing other characters. I'm actually quite beginner in using string.FormatMethods() .
Please help me out.
Thanks.
This should do it:
string test = "samarena -- 192.168.1.97";
var result = test.Split(new string[] { "--" }, StringSplitOptions.None)[0].Trim();
Result will equal samarena
you could split the string on ' -- ' and then use the first part
This should do it.
var yourString = "samarena -- 192.168.1.97";
var indexOfDash = yourString.IndexOf("-");
var yourComputerName = yourString.SubString(0, indexOfDash).Trim();
But the other answers using Trim are better :)
This'd be the totally imperative way.
If You are sure there is always a substring " -- " after the part You want, You can do this
myString.Substring(0, myString.IndexOf(" -- "))
Or use a shorter part of " -- ".
Try this:
char [] chars = {'-'};
string test = "samarena -- 192.168.1.97";
//computerName array will have the Computer Name at the very first index (it is a zero based index
string[] computerName = test.Split(chars,StringSplitOptions.RemoveEmptyEntries);
//computerName[0] is your computerName