This question already has answers here:
How can I deserialize JSON with C#?
(19 answers)
C# string replace does not actually replace the value in the string [duplicate]
(3 answers)
Closed 3 years ago.
List item
I have a string object such as the following.
string mycontent = "\"The time is Valid\"\n"
string tocompare = "The time is Valid"
The contents of mycontent are assigned by the following line of code.
string mycontent = await response.Content.ReadAsStringAsync();
I want to be able to remove all the \n and the \ and to do that I do the following.
mycontent.Trim().Replace(#"\","")
I am trying to compare the mycontent and tocompare for equality. But this does not work.
if (string.Compare(tocompare, mycontent.Trim().Replace(#"\","")) == 0)
{
//TODO
}
For some reason which I do not know, I am not able to see equal to 0.
Am I missing something here? Any help is appreciated.
There are no actual slash characters in the string you showed. The slashes in the source code are part of the string literal syntax, where the \" represents just the character " (it needs to be escaped to distinguish it from the end of the string) and the \n represents a newline.
If you want to remove quotes and newlines from the sides of the string, you can do that with Trim too:
mycontent.Trim('"', '\n')
But that’s a bit of a weird thing to do. If this string actually represents some serialized format for the text you want, like JSON or CSV, you should use a parser for that instead. Where did you get it?
You have to replace slash first and then the quote
mycontent = mycontent.Trim().Replace(#"\", "").Replace(#"""", "")
In your case:
if (string.Compare(tocompare, mycontent.Trim().Replace(#"\","").Replace(#"""", "")) == 0)
{
//TODO
}
If you want to add a text slash to a string, you must type like this.
string mycontent = "\\"+"The time is Valid"+"\\"+"\n";
To delete slashes
mycontent=mycontent.Trim().Replace("\\","");
Related
This question already has an answer here:
ASCII.GetString() stop on null character
(1 answer)
Closed 6 years ago.
I have came across this annoying feature/bug. Assume I have a string with trailing spaces like the following:
string value = "someValue ";
The amount of spaces can vary. So I try to show it in a TextBox enclosed in begin and end tags to see how it varies, and it works perfectly.
textBox1.Text = $"BEGIN#{value}#END";
But the device that send me this value likes to add a \0 null character at the end like this:
string value = "someValue " + Convert.ToChar(0x00);
and when I try to display it with the same method:
textBox1.Text = $"BEGIN#{value}#END;
it results in the disappearance of the #END tag.
The same phenomenon happens in RichTextBox.
Question:
Why does the null character kills/eats the rest of the string?
Is it like in C or C++ that it is interpreted as the end of the char array in a string?
In some languages, such as C and C++, a null character indicates the end of a string. In the .NET Framework, a null character can be embedded in a string. When a string includes one or more null characters, they are included in the length of the total string. For example, in the following string, the substrings "abc" and "def" are separated by a null character. The Length property returns 7, which indicates that it includes the six alphabetic characters as well as the null character.
using System;
using System.Text;
public class StringClassTest
{
public static void Main()
{
string characters = "abc\u0000def";
Console.WriteLine(characters.Length); // Displays 7
}
}
This question already has answers here:
How do I extract text that lies between parentheses (round brackets)?
(19 answers)
Closed 7 years ago.
As I know for selecting a part of a string we use split. For example, if node1.Text is test (delete) if we choose delete
string b1 = node1.Text.Split('(')[0];
then that means we have chosen test, But if I want to choose delete from node1.Text how can I do?
Update:
Another question is that when there are two sets of parenthesis in the string, how one could aim at delete?. For example is string is test(2) (delete) - if we choose delete
You can also use regex, and then just remove the parentheses:
resultString = Regex.Match(yourString, #"\((.*?)\)").Value.
Replace("(", "").Replace(")", "");
Or better:
Regex.Match(yourString, #"\((.*?)\)").Groups[1].Value;
If you want to extract multiple strings in parentheses:
List<string> matches = new List<string>();
var result = Regex.Matches(yourString, #"\((.*?)\)");
foreach(Match x in result)
matches.Add(x.Groups[1].Value.ToString());
If your string is always xxx(yyy)zzz format, you can add ) character so split it and get the second item like;
var s = "test (delete) if we choose delete";
string b1 = s.Split(new[] { '(', ')' })[1];
string tmp = node1.Text.Split('(')[1];
string final = tmp.Split(')')[0];
Is also possible.
With the index [x] you target the part of the string before and after the character you have split the original string at. If the character occurs multiple times, your resulting string hat more parts.
I want to remove first and last double quotes in my json string.
"[{\"CircleID\":1,\"CircleName\":\"Andhra Pradesh\"},{\"CircleID\":4,\"CircleName\":\"Assam\"},{\"CircleID\":5,\"CircleName\":\"Bihar\"},{\"CircleID\":6,\"CircleName\":\"Chennai\"},{\"CircleID\":7,\"CircleName\":\"Delhi\"},{\"CircleID\":8,\"CircleName\":\"Gujarat\"},{\"CircleID\":9,\"CircleName\":\"Himachal Pradesh\"},{\"CircleID\":10,\"CircleName\":\"Haryana\"},{\"CircleID\":17,\"CircleName\":\"Mumbai\"},{\"CircleID\":26,\"CircleName\":\"Jharkhand\"},{\"CircleID\":27,\"CircleName\":\"Chhattisgarh\"}]"
in above json string I want to remove first and last double quotes.how to remove.Iam tried but no use. Iam using string.replce method,string.trim() method but quotes are not removed.please help me.
You can use String.Trim do not forget to assign the result back to string variable. string in c# are immutable and we need to assign the changed value back to the variable.
jsonStr = jsonStr.Trim( '"' );
If you have multiple characters you can use overloaded String.Trim(Char[])
jsonStr = jsonStr.Trim( new Char[] { '"' } );
Edit in OP there is only on double quote in beginning and end of string but if we have multiple double quotes in beginning and end and we just want to remove only first and last then we can use string.Substring
jsonStr = jsonStr.Substring(1, jsonStr.Length-2);
I'm assuming " and \" are actually in the string, and not an artifact of embedding that string in source code or displaying it in the debugger.
In that case, you don't want to just remove the initial and trailing ", but you need to treat it as a json string and decode it. This will also replace the encoded \" by plain " inside the string.
If you're using Newtonsoft Json:
decodedString = JsonConvert.DeserializeObject<string>(jsonString);
this is help for me.
responseContent = responseContent.Substring(1, responseContent.Length - 1);
responseContent = responseContent.Substring(0, responseContent.Length - 1);
This question already has answers here:
How to remove new line characters from a string?
(11 answers)
Closed 9 years ago.
I'm trying to trim a string of some character so I can put it in an SQL query. An example of what is being passed to my method is "\n asdw_value\n". I want the "\n"s and the space to be removed, but I can't get the "\n" to go away. My code now looks like this :
element = element.Replace("\\", "");
element = element.Replace("n", "");
element = element.Replace(" ", "");
And the output has been "\nasdq_value\n" Any help is appreciated.
Most likely the string value you're seeing is produced in the debugger. The \n is an escape sequence meaning 'newline'. It's a single character, not a \ followed by a n, so to remove it from your input, you will need to use the same escape sequence, like this:
element = element.Replace("\n", "");
element = element.Replace(" ", "");
If you only want to trim these characters from the beginning and end of the string, you can do this:
element = element.Trim(new char[] { '\n', ' ' });
This question already has answers here:
Detecting whitespace in textbox
(4 answers)
Closed 4 years ago.
Is there a way to determine if a string has a space(s) in it?
sossjjs sskkk should return true, and sskskjsk should return false.
"sssss".Trim().Length does not seem to work.
How about:
myString.Any(x => Char.IsWhiteSpace(x))
Or if you like using the "method group" syntax:
myString.Any(Char.IsWhiteSpace)
If indeed the goal is to see if a string contains the actual space character (as described in the title), as opposed to any other sort of whitespace characters, you can use:
string s = "Hello There";
bool fHasSpace = s.Contains(" ");
If you're looking for ways to detect whitespace, there's several great options below.
It's also possible to use a regular expression to achieve this when you want to test for any whitespace character and not just a space.
var text = "sossjj ssskkk";
var regex = new Regex(#"\s");
regex.IsMatch(text); // true
Trim() will only remove leading or trailing spaces.
Try .Contains() to check if a string contains white space
"sossjjs sskkk".Contains(" ") // returns true
This functions should help you...
bool isThereSpace(String s){
return s.Contains(" ");
}