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 (™, ®)
Related
I have this code written in C# but looks kind of "bad" and I would like to shorten it somehow and keep it clean and simple.
All this code works pretty fine but I want to know if there's any other way I can achieve the same thing.
EDIT: I forgot to mention that the firstLine has a bad date format attached with it, so it is like this: "This_is_my_first_line_20220126". So I split the string and then only join it with the corrected date. The problem is that I can never know how long the new string would be and I don't want to handle the code like this and go up to 100 parts.
Here's my code:
string correctDate = "26012022";
string[] lines = File.ReadAllLines("text.txt");
string firstLine = lines.FirstOrDefault();
//note: firstLine looks like this: This_is_my_first_line_20220126
string[] sub = firstLine.Split('_');
string name="";
if(sub.Length==2)
name = sub[0]+"_"+sub[1]+"_"+correctDate;
else if(sub.Length==3)
name = sub[0]+"_"+sub[1]+"_"+sub[2]+"_"correctDate;
...
else if(sub.Length==20)
name = sub[0]+"_"+ ... "_" + sub[19];
Now, my final name value should be "This_is_my_line_26012022" but I want it to depend on the length of the given string. So far I know that the maximum length would go up to 20 but I don't want my code to look like this. Can I shorten it somehow?
you can find the LastIndexOf the underscore and drop the date by using Substring:
string firstLine = "This_is_my_first_line_20220126";
string correctDate = "26012022";
string correctString = firstLine.Substring(0, firstLine.LastIndexOf("_") + 1) + correctDate;
Still a little perplexed with the split aproach, but this a way to join back all elements
string name = string.Join("_", sub.Take(sub.Length - 1).Append(correctDate));
Or use the substring method (and no need of all that split & join)
name = firstLine.Substring(0, firstLine.LastIndexOf("_") +1) + correctDate;
I forgot to mention that firstLine has a bad date format like "This_is_my_Line_20220125"
If you want to correct just the first line:
string correctDate = "26012022";
string[] lines = File.ReadAllLines("text.txt");
lines[0] = lines[0][..^8] + correctDate;
[..^8] uses C# 9's "indices and ranges" feature, that allows for a more compact way of taking a substring. It means "from the start of the string, up to the index 8 back from the end of the string".
If you get a wiggly line and possibly a messages like "... is not available in C# version X" you can use the older syntax, which would be more like lines[0] = lines[0].Remove(lines[0].Length - 8) + correctDate;
If you want to correct all lines:
string correctDate = "26012022";
string[] lines = File.ReadAllLines("text.txt");
for(int x = 0; x < lines.Length; x++)
lines[x] = lines[x][..^8] + correctDate;
If the incorrect date isn't always 8 characters long, you can use LastIndexOf('_') to locate the last _, and snip it to that point
I am getting a frustratingly weird Form
I've also tried changing it to job.Tags |= Convert.ToInt32(item, CultureInfo.InvariantCulture) but even that gives the same exception.
I have absolutely no idea why.
Here is a character representation of item
And here is my code
if (model.TagSelection != null)
{
foreach (var item in model.TagSelection)
{
job.Tags |= Convert.ToInt32(item, CultureInfo.InvariantCulture);
}
}
Item Length is 5 - the numeric characters are delimited by double quotes (as you'd code but not expect to see in captured data). Since you are getting the string "256", you'll have to Replace() them with string.Empty to get a numerics-only string length 3, which should then convert.
var s = "\"256\"";
var s2 = s.Replace("\"", string.Empty);
Edit: I just realized it's worse than it appears. I think those are left- and right-slanted quotes (note the character codes 823x). You may need something more like this...
var s3 = new string(s.Where(char.IsDigit).ToArray());
The issue has come from copying the values from Excel, not sure why it is doing it but after deleting it and retyping it the error has gone away.
I have a csv file.
When I try to read that file using filestream readtoend(), I get inverted commas and \r at many places that breaks my number of rows in each column.
Is there a way to remove inverted commas and \r.
I tried to replace
FileStream obj = new FileStream();
string a = obj.ReadToEnd();
a.Replace("\"","");
a.Replace("\r\"","");
When I visualize a all \r and inverted commas are removed.
But when I read the file again from beginning using ReadLine() they appear again?
First of all, a String is immutable. You might think this is not important for your question, but actualy it's important whenever you are developing.
If I look at your code snippet, I'm pretty sure you have no knowledge of immutable objects so I advice you to make sure you fully understand the concept.
More information regarding immutable objects can be found: http://en.wikipedia.org/wiki/Immutable_object
Basicly, it means one can never modify a string object. Strings will always point to a new object whenever we change the value.
That's why the Replace method returns a value, which's documentation can be found here: https://msdn.microsoft.com/en-us/library/system.string.replace%28v=vs.110%29.aspx and states clearly that it Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string.
In your example, you aren't using the return value of the Replace function.
Could you show us that the string values are actuably being replaced from your a variable? Because I do not believe this is going to be the case. When you visualize a string, carriage returns (\r) are not visual and replaced by an actual carriage return. If you debug and take alook at the actual string value, you should still see the \n.
Take the following code snippet:
var someString = "Hello / world";
someString.Replace("/", "");
Console.Log(someString);
You might think that the console will show "Hello world". However, on this fiddle you can see that it still logs "Hello / World": https://dotnetfiddle.net/cp59i3
What you have to do to correctly use String.Replace can be seen in this fiddle: https://dotnetfiddle.net/XCGtOu
Basicly, you want to log the return value of the Replace function:
var a = "Some / Value";
var b = a.Replace("/", "");
Console.WriteLine(b);
Also, as mentioned by others in the comment section at ur post, you are not replacing the contents of the file, but the string variable in your memory.
If you want to save the new string, make sure to use the Write method of the FileStream (or any other way to write to a file), an explanation can be found here: How to Find And Replace Text In A File With C#
Apart from all what I have been saying throughout this answer, you should not replace both inverted comma's and carriage returns in a file in most cases, they are there for a reason. Unless you do have a specific reason.
At last I succeeded. Thanks to everybody. Here is the code I did.
FileStream obj = new FileStream();
using(StreamReader csvr = new StreamReader(obj))
{
string a = obj.ReadToEnd();
a = a.Replace("\"","");
a = a.Replace("\r\"","");
obj.Dispose();
}
using(StreamWriter Wr = new StreamWriter(TempPath))
{
Wr.Write(a);
}
using(StreamReader Sr = new StreamReader(Tempath))
{
Sr.ReadLine();
}
I Created a temp path on the system. After this things were easy to enter into database.
Try something like this
StreamReader sReader = new StreamReader("filename");
string a = sReader.ReadToEnd();
a.Replace("\"", "");
a.Replace("\r\"", "");
StringReader reader = new StringReader(a);
string inputLine = "";
while ((inputLine = reader.ReadLine()) != null)
{
}
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 #?
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;
}