How To Remove the Symbol from the string - c#

i am having the string like this
string value="{\"email\":\"test#example.com\",\"password\":\"passworddata\"}"
i want to remove this symbol("\")
and i want string as like this
"{"email":"gg.com","password":"ff"}"

The backslashes are automatically escaped u shouldn't need to do anything.

If you don't mind, you could try this code:
string result = value.Replace("\\", string.Empty);

That looks like it could be JSON; although, you're representing it as an embedded C# string.
Let's say it was this in c#
string value = "{\\\"email\\\":\\\"xxx#example.com\\\",\\\"password\\\":\\\"passworddata\\\"}";
that on console output looked like:
{\"email\":\"xxx#example.com\",\"password\":\"passworddata\"}
You could use regex to strip the escapes:
var val = Regex.Replace(value, "\\\\([^\\\\])", "$1");
so that on output you would have:
{"email":"xxx#example.com","password":"passworddata"}

I think this may help you:
public string Formatter(string MainText, char CharToRemove)
{
string result = MainText;
foreach (char c in result)
{
if(c == CharToRemove)
result = result.Remove(result.IndexOf(c), 1);
}
return result;
}

Try This:
string value = "{\"email\":\"xxx#gamil.com\",\"password\":\"passworddata\"}";
value="\"" + value.Replace("\\", "") + "\"";
Output:
"{"email":"gg.com","password":"passworddata"}"

Place the edit cursor (I-bar) behind each \ character and press Bksp
As per King King's request:
An aternative method would be to place the I-bar in front of the \ and press Del

Related

Remove substring if exists

I have 3 possible input cases
string input = ""; // expected result: ""
string input = "bar-foo"; // expected result: "foo"
string input = "foo"; // expected result: "foo"
And I have to remove everyting including the first separator char - if exists.
Working approach:
string output = input.Split('-').LastOrDefault();
I want to solve this without Split() - my NOT working approach:
string output = input.Substring(input.IndexOf('-') );
How can I handle the IndexOutOfRangeException / make this code work?
Try to add 1:
string output = input.Substring(input.LastIndexOf('-') + 1);
If there's no - in the input, LastIndexOf returns -1 and so you'll have the entire string.
I've assumed that your are looking for input's suffix, that's why I've put LastIndexOf:
"123-456-789" -> "789"
If you want to cut off the prefix:
"123-456-789" -> "456-789"
please, change LastIndexOf into IndexOf
i think you should use Contains Method to identify - is available or not.
string a = "";
if (a.Contains("-"))
{
string output = input.Substring(input.LastIndexOf('-') + 1);
}
Why not just remove it from the string without checking:
input = input.Replace("-foo", string.Empty);

Replacing characters in a string with another string

So what I am trying to do is as follows :
example of a string is A4PC
I am trying to replace for example any occurance of "A" with "[A4]" so I would get and similar any occurance of "4" with "[A4]"
"[A4][A4]PC"
I tried doing a normal Replace on the string but found out I got
"[A[A4]]PC"
string badWordAllVariants =
restriction.Value.Replace("A", "[A4]").Replace("4", "[A4]")
since I have two A's in a row causing an issue.
So I was thinking it would be better rather than the replace on the string I need to do it on a character per character basis and then build up a string again.
Is there anyway in Linq or so to do something like this ?
You don't need any LINQ here - String.Replace works just fine:
string input = "AAPC";
string result = input.Replace("A", "[A4]"); // "[A4][A4]PC"
UPDATE: For your updated requirements I suggest to use regular expression replace
string input = "A4PC";
var result = Regex.Replace(input, "A|4", "[A4]"); // "[A4][A4]PC"
This works well for me:
string x = "AAPC";
string replace = x.Replace("A", "[A4]");
EDIT:
Based on the updated question, the issue is the second replacement. In order to replace multiple strings you will want to do this sequentially:
var original = "AAPC";
// add arbitrary room to allow for more new characters
StringBuilder resultString = new StringBuilder(original.Length + 10);
foreach (char currentChar in original.ToCharArray())
{
if (currentChar == 'A') resultString.Append("[A4]");
else if (currentChar == '4') resultString.Append("[A4]");
else resultString.Append(currentChar);
}
string result = resultString.ToString();
You can run this routine with any replacements you want to make (in this case the letters 'A' and '4' and it should work. If you would want to replace strings the code would be similar in structure but you would need to "look ahead" and probably use a for loop. Hopefully this helps!
By the way - you want to use a string builder here and not strings because strings are static which means space gets allocated every time you loop. (Not good!)
I think this should do the trick
string str = "AA4PC";
string result = Regex.Replace(str, #"(?<Before>[^A4]?)(?<Value>A|4)(?<After>[^A4]?)", (m) =>
{
string before = m.Groups["Before"].Value;
string after = m.Groups["After"].Value;
string value = m.Groups["Value"].Value;
if (before != "[" || after != "]")
{
return "[A4]";
}
return m.ToString();
});
It is going to replace A and 4 that hasn't been replaced yet for [A4].

Regex.Match doesnt work correctly

I have a string extension that was defined exactly like this:
public static string GetStringBetween(this string value, string start, string end)
{
start = Regex.Escape(start);
end = Regex.Escape(end);
GroupCollection matches = Regex.Match(value, start + #"([^)]*)" + end).Groups;
return matches[1].Value;
}
But when I call this:
string str = "The pre-inspection image A. Valderama (1).jpg of client Valderama is not...";
Console.WriteLine(str.GetStringBetween("pre-inspection image ", " of client"));
It doesn't write anything. But when the str value is like this:
string str = "The pre-inspection image A. Valderama.jpg of client Valderama is not...";
It works fine. Why was it like this?
My code is in C#, framework 4, build in VS2010 Pro.
Please help. Thanks in advance.
Because you specify to exclude the character ) in the capturing group of your regex: [^)] in #"([^)]*)"
And since ) appears in the first string: Valderama (1).jpg, it will not be able to match.
You probably want #"(.*)" instead.

How to select only the characters after a repeated symbol in a long string

If i am using C# and i have a string coming in from a database like this:
\RBsDC\1031\2011\12\40\1031-215338-5DRH44PUEM2J51GRL7KNCIPV3N-META-ENG-22876500BBDE449FA54E7CF517B2863E.XML
And i only want this part of the string:
1031-215338-5DRH44PUEM2J51GRL7KNCIPV3N-META-ENG-22876500BBDE449FA54E7CF517B2863E.XML
How can i get this string if there is more than one "\" symbol?
You can use the LastIndexOf() method of the String class:
string s = #"\RBsDC\1031\2011\12\40\1031-215338-5DRH44PUEM2J51GRL7KNCIPV3N-META-ENG-22876500BBDE449FA.xml";
Console.Out.WriteLine(s.Substring(s.LastIndexOf('\\') + 1));
Hope, this helps.
Use String.Split to split string by parts and then get the last part.
Using LINQ Enumerable.Last() :
text.Split('\\').Last();
or
// todo: add null-empty checks, etcs
var parts = text.Split('\\');
strign lastPart = parts[parts.Length - 1];
You can use a combination of String.LastIndexOf("\") and String.Substring(lastIndex+1). You could also use (only in the sample you provided) Path.GetFileName(theString).
string[] x= line.Split('\');
string goal =x[x.Length-1];
but linq will be easier
You can use regex or split the string by "\" symbol and take the last element of array
using System.Linq;
public class Class1
{
public Class1()
{
string s =
#"\RBsDC\1031\2011\12\40\1031-215338-5DRH44PUEM2J51GRL7KNCIPV3N-META-ENG-22876500BBDE449FA54E7CF517B2863E.XML";
var array = s.Split('\\');
string value = array.Last();
}
}
newstring = string.Substring(string.LastIndexOf(#"\")+1);
It seems like original string is like filePath.
This could be one easy solution.
string file = #"\RBsDC\1031\2011\12\40\1031-215338-5DRH44PUEM2J51GRL7KNCIPV3N-META-ENG-22876500BBDE449FA.xml";
string name = System.IO.Path.GetFileName(file);

Convert string in to number?

I have a string like "3.9" I want to convert this string in to a number without using split function.
If string is 3.9 => o/p 39
If string is 1.2.3 => o/p 123
I'm not sure what the purpose is. Would it work for your case to just remove the periods and parse the number?
int result = Int32.Parse(str.Replace(".", String.Empty));
You could remove replace the . with empty string before trying to parse it:
string inputString = "1.2.3";
int number = int.Parse(inputString.Replace(".", ""));
string str = "3.9";
str = str.Replace(".","");
int i;
int.TryParse(str, out i);
I would probably go with something like this:
string str = "3.2";
str = str.Replace(".", "");
double number = convert.ToDouble(str);
you can use Replace(".",""); for this purpose
eg:
string stnumber= "5.9.2.5";
int number = Convert.ToInt32(stnumber.Replace(".", ""));
i think Convert.ToInt32(); is better than int.Parse();

Categories

Resources