Substring issue - c#

I have the below code:
sDocType = pqReq.Substring(0, pqReq.IndexOf(#"\t"));
The string pqReq is like this: "CSTrlsEN\t001\t\\sgprt\Projects2\t001\tCSTrl". But even though I can clearly see the t\ in the string, pqReq.IndexOf(#"\t") returns -1, so an error is thrown.
What's the correct way to do this? I don't want to split the string pqReq until later on in the code.

Use \\t instead of \t. The \t is seen as a tab-character. sDocType = pqReq.Substring(0, pqReq.IndexOf(#"\t"));
Edit:
I didn't notice the \t being literal due to the #. But is your input string a literal string? If not, place an # before the value of pqReq.
string pqReq = #"CSTrlsEN\t001\t\\sgprt\Projects2\t001\tCSTrl";
int i = pqReq.IndexOf(#"\t");
//i = 8

I can't reproduce this issue. The following code (.NET Fiddle here):
var pqReq=#"CSTrlsEN\t001\t\\sgprt\Projects2\t001\tCSTrl";
var idx=pqReq.IndexOf(#"\t");
Console.WriteLine(idx);
var sDocType = pqReq.Substring(0, idx);
Console.WriteLine(sDocType);
produces:
8
CSTrlsEN
Did you forget to prefix pqReq with #?

Related

String concatenation using String interpolation

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.

How to place double quotes inside the double quotes of string.IndexOf() function?

I have a String I want to get the index of the "id:" i.e the id along with the double quotes.
How I am supposed to do so inside C# string.IndexOf function?
This will get the index of the string you want:
var idx = input.IndexOf("\"id:\"");
if you wanted to pull it out you'd do something like this maybe:
var idx = input.IndexOf("\"id:\"");
var val = input.Substring(idx, len);
where len is either a statically known length or also calculated by another IndexOf statement.
Honestly, this could also be done with a Regex, and if an example were available a Regex may be the right approach because you're presumably trying to get the actual value here and it's presumably JSON you're reading.
" is an escape sequence
If you want to use a double quotation mark in your string, you should use \" instead.
For example;
int index = yourstring.IndexOf("\"id:\"");
Remember, String.IndexOf method gets zero-based index of the first occurrence of the your string.
This is a simple approach: If you know double quote is before the Id then take index of id - 1?
string myString = #"String with ""id:"" in it";
var indexOfId = myString.IndexOf("id:") - 1;
Console.WriteLine(#"Index of ""id:"" is {0}", indexOfId);
Reading between the lines, if this is a JSON string, and you have .NET 4 or higher available, you can ask .NET to deserialize the string for you rather than parsing by hand: see this answer.
Alternatively you might consider Json.NET if you're working very heavily with JSON.
Otherwise, as others note, you need to escape the quotes, so for example:
text.IndexOf("\"id:\"")
text.IndexOf(#"""id:""")
or for overengineered legiblity:
string Quoted(string text)
{
return "\"" + text + "\""; // generates unnecessary garbage
}
text.IndexOf(Quoted("id:"))

C# string.Replace doesn't work

Basically our Problem is:
We can't replace a string like this: 10003*
But we can replace a string like this: 10003
we want to replace a part of a string that looks like this: 10003*
This is our Code:
string text = sr2.ReadToEnd();
sr2.Close();
while (loop != lstTxt.Items.Count)
{
string SelectedItem = lstTxt.SelectedItem.ToString() + "*";
text = text.Replace(SelectedItem, "tietze111");
if (lstTxt.SelectedIndex < lstTxt.Items.Count - 1)
lstTxt.SelectedIndex++;
loop++;
}
sw2.Write(text);
But it doesn't work. When we leave out the * in the part to replace, it works. But we have to replace the * too. Do you know what we have to change?
It works when we use this:
string text = sr2.ReadToEnd();
sr2.Close();
while (loop != lstTxt.Items.Count)
{
string SelectedItem = lstTxt.SelectedItem.ToString(); // changed
text = text.Replace(SelectedItem, "tietze111");
if (lstTxt.SelectedIndex < lstTxt.Items.Count - 1)
lstTxt.SelectedIndex++;
loop++;
}
sw2.Write(text);
--
using (var sr2 = new StreamReader(Application.StartupPath + #"\website\Dehler 22 ET.htm", Encoding.Default))
{
using (var sw2 = new StreamWriter(tempFile, true, Encoding.Default))
We are using this because the file is still in ASCII. Maybe that is the problem.
How do we solve this?
Fix the following line,
string SelectedItem = lstTxt.SelectedItem.Value;
You are taking the item and not the value.
Have you tried?
"[\*]"
Or
#"[*]"
The String.Replace(String,String) method doesn't do anything special with any characters. There is a character in your id that you are trying to replace is not the same as the one you are trying to match on. I would try copying the astrisk from the data source into your code and see if the problem still exists.
Your problem * is encoded in some other type. The Unicode value for asterisk U+002A
You could try this. Note Char.MinValue is technically a null value since you cannot have a blank Char.
In your case: lstTxt.SelectedItem.ToString() + '\u002A'.ToString();
If that doesn't work try removing (using different encoded values for *) to make sure you can actually find it in the string.
SomeString.Replace('\u002A', Char.MinValue);
OR
SomeString.Replace('\u002A'.ToString(), String.Empty);
I've ran into issues like this before and it ends up being a trial and error kind of thing until you get it right. Similar problem I had last summer C# String.Replace not finding / replacing Symbol (™, ®)

How to remove characters from a string to get the desired format?

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

Remove characters after specific character in string, then remove substring?

I feel kind of dumb posting this when this seems kind of simple and there are tons of questions on strings/characters/regex, but I couldn't find quite what I needed (except in another language: Remove All Text After Certain Point).
I've got the following code:
[Test]
public void stringManipulation()
{
String filename = "testpage.aspx";
String currentFullUrl = "http://localhost:2000/somefolder/myrep/test.aspx?q=qvalue";
String fullUrlWithoutQueryString = currentFullUrl.Replace("?.*", "");
String urlWithoutPageName = fullUrlWithoutQueryString.Remove(fullUrlWithoutQueryString.Length - filename.Length);
String expected = "http://localhost:2000/somefolder/myrep/";
String actual = urlWithoutPageName;
Assert.AreEqual(expected, actual);
}
I tried the solution in the question above (hoping the syntax would be the same!) but nope. I want to first remove the queryString which could be any variable length, then remove the page name, which again could be any length.
How can I get the remove the query string from the full URL such that this test passes?
For string manipulation, if you just want to kill everything after the ?, you can do this
string input = "http://www.somesite.com/somepage.aspx?whatever";
int index = input.IndexOf("?");
if (index >= 0)
input = input.Substring(0, index);
Edit: If everything after the last slash, do something like
string input = "http://www.somesite.com/somepage.aspx?whatever";
int index = input.LastIndexOf("/");
if (index >= 0)
input = input.Substring(0, index); // or index + 1 to keep slash
Alternately, since you're working with a URL, you can do something with it like this code
System.Uri uri = new Uri("http://www.somesite.com/what/test.aspx?hello=1");
string fixedUri = uri.AbsoluteUri.Replace(uri.Query, string.Empty);
To remove everything before the first /
input = input.Substring(input.IndexOf("/"));
To remove everything after the first /
input = input.Substring(0, input.IndexOf("/") + 1);
To remove everything before the last /
input = input.Substring(input.LastIndexOf("/"));
To remove everything after the last /
input = input.Substring(0, input.LastIndexOf("/") + 1);
An even more simpler solution for removing characters after a specified char is to use the String.Remove() method as follows:
To remove everything after the first /
input = input.Remove(input.IndexOf("/") + 1);
To remove everything after the last /
input = input.Remove(input.LastIndexOf("/") + 1);
Here's another simple solution. The following code will return everything before the '|' character:
if (path.Contains('|'))
path = path.Split('|')[0];
In fact, you could have as many separators as you want, but assuming you only have one separation character, here is how you would get everything after the '|':
if (path.Contains('|'))
path = path.Split('|')[1];
(All I changed in the second piece of code was the index of the array.)
The Uri class is generally your best bet for manipulating Urls.
To remove everything before a specific char, use below.
string1 = string1.Substring(string1.IndexOf('$') + 1);
What this does is, takes everything before the $ char and removes it. Now if you want to remove the items after a character, just change the +1 to a -1 and you are set!
But for a URL, I would use the built in .NET class to take of that.
Request.QueryString helps you to get the parameters and values included within the URL
example
string http = "http://dave.com/customers.aspx?customername=dave"
string customername = Request.QueryString["customername"].ToString();
so the customername variable should be equal to dave
regards
I second Hightechrider: there is a specialized Url class already built for you.
I must also point out, however, that the PHP's replaceAll uses regular expressions for search pattern, which you can do in .NET as well - look at the RegEx class.
you can use .NET's built in method to remove the QueryString.
i.e., Request.QueryString.Remove["whatever"];
here whatever in the [ ] is name of the querystring which you want to
remove.
Try this...
I hope this will help.
You can use this extension method to remove query parameters (everything after the ?) in a string
public static string RemoveQueryParameters(this string str)
{
int index = str.IndexOf("?");
return index >= 0 ? str.Substring(0, index) : str;
}

Categories

Resources