replace string with double quotes - c#

I want to replace, from a JSON file :"[" to :["
The below runs but without delivering the expected.Any clues?(I looked in similar questions, but I was more confused)
string contenty = contentx.Replace(":"["",":["");
return contentx;

You're returning contentx instead of contenty. contenty is the variable that has the new string.

First you have to escape the double quotes with \"
Then you have to return the "return value" of the expression in the same variable, or simply use one return statement:
return contentx.Replace(":\"[\"", ":[\"");

Try it like this (you have some issues with the double quotes in a string):
return contentx.Replace(#":""[""", #":[""");
Another option is:
return contentx.Replace(":\"[\"", ":[\"");
This will make sure that the character escaping goes well and your string is replaced properly. Moreover, as Equalsk showed in his comment, this will also solve the problem of returning the wrong variable and creating an unnecessary variable.

Related

Remove characters in string in C#

I have the following field that is calling the database Phone_Number. I would like to remove the 1- when the number is displayed.
So instead of displaying 1-###-###-####, I would like to display ###-###-####.
I tried the following:
string x= Phone_Number;
x.Remove(0,1);
Response.Write(x);
However, it keeps displaying 1-###-###-####.
What am I doing wrong?
Strings are immutable in C# - String.Remove call does not modify original string. It creates the new string in which specified characters are deleted and returns it. You should display result of this method call instead:
Response.Write(x.Remove(0,2)); // you should remove 2 characters
Or
Response.Write(x.Substring(2));
You need to set the result to x. strings are immutable in C#:
x = x.Remove(0,1)
Another method would be:
if (x.StartsWith("1-")
x = x.Remove(0,2);
This has the benefit of doing nothing if you get a phone number without the leading 1-.
Thanks to commenter for pointing out my error.
As you see there are too many ways to remove substrings from strings. A new way that you can also use is a Regular Expression just in case the value you want to remove have a complex pattern in the future.
var x = phoneNumber;
var result = Regex.Match(x, #"^(1-)?(.*)$").Groups[2].Value;

Parsing out Excel functions from Formula string

I have a string which contains an Excel formula. How to parse out each particular function name from within the string?
I can't figure out how to write the regex for this. Basically it has to be the string of characters before a ( that isn't in a single or double quote.
For example:
=VLOOKUP($A9,'Summary'!$A$10:$C$30,3,FALSE) - Should return VLOOKUP
=IFERROR((C10/B10),"N/A") - should return IFERROR
='New Chart Data (Date)'!L70 - Should return nothing because there is no function
=IFERROR((C10/B10),Len(E30)) - should return IFERROR and LEN
='New Chart Data(Date)'!L70 + Len(5) - should return Len. This is the tricky one. A lot will return Data as well which is wrong.
Any ideas?
Thanks in advance.
You can use something like this I guess...
(?<=[=,])[A-Za-z2]+(?=\()
regex101 demo (with descriptions of regex)
Actually, there's one catch: a formula such as =IFERROR((C10/B10), Len(E30)) won't get Len. You can use this one instead and trim any spaces if any:
(?<=[=,])\s*[A-Za-z2]+(?=\()
Or since C# accepts variable length lookbehinds...
(?<=[=,]\s*)[A-Za-z2]+(?=\()
Which I think takes a bit more resources than the previous.
EDIT: I didn't think of the fact that sheetnames can take the form =Sheet(2) e.g. ='=Sheet(2)'!A1
(?<=[=,])\s*[A-Za-z2]+(?=\()(?![^']*'!)
revised regex101
EDIT2: Forgot operators as well... I guess I'll use a word boundary like Andy's, since the only issue is
\b[A-Za-z2]+(?=\()(?![^']*'!)
updated regex101
I think it could be simplified, using a word-break \b rather than a look-behind:
\b([A-Za-z2]+)(?=\()

about string removing in C#

Whats is correct to do?
check if exists, then remove?
var input = "foo #main baa";
if(input.Contains("#main")) {
input = input.Replace("#main", "");
}
or just:
input = input.Replace("#main", "");
Well, this seem a simple question,but I really want know.
Thanks in advance.
The Contains check actually just makes your code slower.
Remove it.
The Contains call needs to loop through the string until it finds #main.
The Replace call then needs to do the same exact loop (it can't remember it from the Contains call).
This is a Shlemiel the Painter's algorithm.
Replace can handle strings with zero or more occurrences of the search string, so you don't need the check.
Just do the replacement - if it's not there, nothing should happen.
Just make the call to Replace(). If the substring isn't found nothing happens and you avoid an additional call to Contains().
I would do this:
input = input.Replace("#main", "").Replace(" "," ");
To remove any double spaces.
Just remove it. The only thing to check is if the string is null or not.

.NET string IndexOf unexpected result

A string variable str contains the following somewhere inside it: se\">
I'm trying to find the beginning of it using:
str.IndexOf("se\\\">")
which returns -1
Why isn't it finding the substring?
Note: due to editing the snippet showed 5x \ for a while, the original had 3 in a row.
Your code is in fact searching for 'se\\">'. When searching for strings including backslashes I usually find it easier to use verbatim strings:
str.IndexOf(#"se\"">")
In this case you also have a quote in the search string, so there is still some escaping, but I personally find it easier to read.
Update: my answer was based on the edit that introduced extra slashes in the parameter to the IndexOf call. Based on current version, I would place my bet on str simply not containing the expected character sequence.
Update 2:
Based on the comments on this answer, it seems to be some confusion regarding the role of the '\' character in the strings. When you inspect a string in the Visual Studio debugger, it will be displayed with escaping characters.
So, if you have a text box and type 'c:\' in it, inspecting the Text property in the debugger will show 'c:\\'. An extra backslash is added for escaping purposes. The actual string content is still 'c:\' (which can be verified by checking the Length property of the string; it will be 3, not 4).
If we take the following string (taken from the comment below)
" '<em
class=\"correct_response\">a
night light</em><br
/><br /><table
width=\"100%\"><tr><td
class=\"right\">Ingrid</td></tr></table>')"
...the \" sequences are simply escaped quotation marks; the backslashes are not part of the string content. So, you are in fact looking for 'se">', not 'se\">'. Either of these will work:
str.IndexOf(#"se"">"); // verbatim string; escape quotation mark by doubling it
str.IndexOf("se\">"); // regular string; escape quotation mark using backslash
This works:
string str = "<case\\\">";
int i = str.IndexOf("se\\\">"); // i = 3
Maybe you're not correctly escaping one of the two strings?
EDIT there's an extra couple of \ in the string you are searching for.
Maybe the str variable does not actually contain the backslash.
It may be just that when you mouse over the variable while debugging, the debugger tooltip will show the escape character.
e.g. If you put a breakpoint after this assignment
string str = "123\"456";
the tooltip will show 123\"456 and not 123"456.
However if you click on the visualize icon, you will get the correct string 123"456
Following code:
public static void RunSnippet()
{
string s = File.ReadAllText (#"D:\txt.txt");
Console.WriteLine (s);
int i = s.IndexOf("se\\\">");
Console.WriteLine (i);
}
Gives following output:
some text before se\"> some text after
17
Seems like working to me...
TextBox2.Text = TextBox1.Text.IndexOf("se\"">")
seems to work in VB.
DoubleQuotes within a string need to be specified like "" Also consider using verbatim strings - So an example would be
var source = #"abdefghise\"">jklmon";
Console.WriteLine(source.IndexOf(#"se\"">")); // returns 8
If you are looking for se\">
then
str.IndexOf(#"se\"">")
is less error-prone. Note the double "" and single \
Edit, after the comment: it seems like the string may contain ecaping itself, in which case in se\"> the \" was an escaped quote, so the literal text is simply se"> and the string to use is Indexof("se\">")

Simple way to trim Dollar Sign if present in C#

I have a DataRow and I am getting one of the elements which is a Amount with a dollar sign. I am calling a toString on it. Is there another method I can call on it to remove the dollar sign if present.
So something like:
dr.ToString.Substring(1, dr.ToString.Length);
But more conditionally in case the dollar sign ever made an appearance again.
I am trying to do this with explicitly defining another string.
Convert.ToString(dr(columnName)).Replace("$", String.Empty)
--
If you are working with a data table, then you have to unbox the value (by default its Object) to a string, so you are already creating a string, and then another with the replacement. There is really no other way to get around it, but you will only see performance differences when dealing with tens of thousands of operations.
You could also use
string trimmed = (dr as string).Trim('$');
or
string trimmed = (dr as string).TrimStart('$');
If you are using C# 3.0 or greater you could use extension methods.
public static string RemoveNonNumeric(this string s)
{
return s.Replace("$", "");
}
Then your code could be changed to:
((String)dr[columnName]).RemoveNonNumeric();
This would allow you to change the implementation of RemoveNonNumeric later to remove things like commas or $ signs in foreign currency's, etc.
Also, if the object coming out of the database is indeed a string you should not call ToString() since the object is already a string. You can instead cast it.
Regex would work.
Regex.Replace(theString, "$", "");
But there are multiple ways to solve this problem.
dr[columeName].ToString().Replace("$", String.Empty)
Why don't you update the database query so that it doesn't return the dollar sign? This way you don't have to futz with it in your C# code.

Categories

Resources