string s = "apple]","[banana...." ;
I need to remove ( "]","[ ) and replace with "," from above string so that the output looks like below:
s = "apple,banana...."
s = s.Replace(#"\]","[\", ","); //something like this?
You need to escape the quotation marks in the string. You have tried to escape something, but \ isn't used to escape characters in a # delimited string.
In a # delimited string you use "" to escape ":
s = s.Replace(#"]"",""[", ",");
In a regular string you use \" to escape ":
s = s.Replace("]\",\"[", ",");
I assume it is a string[]?
I propose something like this:
string[] s = {"[apple]","[banana]","[orange]"} ;
string new_s = "";
foreach (string ss in s)
{
new_s += ss.Replace("[", "").Replace("]", ",");
}
//handle extra "," at end of string
new_s = new_s.Remove(new_s.Length-1);
Edit: Disregard, I misunderstood what you were trying to accomplish due to syntactical errors in your string definition.
string s = "apple]","[banana...." ;
should be:
string s = "apple]\",\"[banana....";
Related
I have the value 4,59,999/-. My code is
if (Regex.IsMatch(s,#"\b[1-9]\d*(?:,[0-9]+)*/?-?"))
{
string value = Regex.Replace(s, #"[^\d]", " ");
textBox2.Text= value;
}
Output is: 4 59 999, I need it to be 459999 (without "," , "/" , "-" and " ").
How about without regex?
var s = "4,59,999/-";
var array = s.Where(c => char.IsDigit(c)).ToArray();
or shorter
var array = s.Where(char.IsDigit).ToArray();
And you can use this array in a string(Char[]) constructor.
var result = new string(array); // 459999
You don't need regex, you could use:
textBox2.Text = String.Concat(s.Where(Char.IsDigit));
Much better is to use decimal.Parse/TryParse:
string s = "4,59,999/-.";
decimal price;
if (decimal.TryParse(s.Split('/')[0], NumberStyles.Currency, NumberFormatInfo.InvariantInfo, out price))
textBox2.Text = price.ToString("G");
Just replace with empty string.
string value = Regex.Replace(s, #"[^\d]", ""); // See the change in the replace string.
textBox2.Text= value;
Note You don't require the if as the regex replace will work only if there is a match for non digits ([^\d])
Should just be a case of replacing it with an empty string instead of a space?
Regex.Replace(s, #"[^\d]", String.Empty);
Currently you're replacing these characters with a space. Use an empty set of quotes instead.
if (Regex.IsMatch(s,#"\b[1-9]\d*(?:,[0-9]+)*/?-?"))
{
string value = Regex.Replace(s, #"[^\d]", "");
textBox2.Text= value;
}
You are replacing the ",", "/", "-" and " " with a white space. Try this instead:
string value = Regex.Replace(s, #"[^\d]", "");
Hope this helps.
Linq is a possible solution:
String s = "4,59,999/-";
...
textBox2.Text = new String(s.Where(item => item >= '0' && item <= '9').ToArray());
Try something like this it will work 100% in php so just change some syntax for C#
<?php
$str = "4,59,999/-.";
echo $str = preg_replace('/[^a-z0-9]/', '', $str);
?>
I have a string called fileNameArrayEdited which contains "\\windows".The below if statement is not running.
Thinking the problem is else where as people have given me code that should work will be back once I found the problem... thanks!
if (fileNameArrayEdited.StartsWith("\\"))
{
specifiedDirCount = specifiedDirCount + 1;
}
// Put all file names in root directory into array.
string[] fileNameArray = Directory.GetFiles(#specifiedDir);
int specifiedDirCount = specifiedDir.Count();
string fileNameArrayEdited = specifiedDir.Remove(0, specifiedDirCount);
Console.WriteLine(specifiedDir.Remove(0, specifiedDirCount));
if (fileNameArrayEdited.StartsWith(#"\\"))
{
specifiedDirCount = specifiedDirCount + 1;
Console.ReadLine();
Use '#' at the beginning of your string if you are searching for exactly two slash
if (fileNameArrayEdited.StartsWith(#"\\"))
{
specifiedDirCount = specifiedDirCount + 1;
}
They are called verbatim strings and they are ignoring escape characters.For better explanation you can take a look at here: http://msdn.microsoft.com/en-us/library/362314fe.aspx
But I suspect in here your one slash is escape character
"\\windows"
So you must search for one slash like this:
if (fileNameArrayEdited.StartsWith(#"\"))
{
specifiedDirCount = specifiedDirCount + 1;
}
When we write
string s1 = "\\" ;
// actual value stored in s1 is "\"
string s2 = #"\\" ;
// actual value stored in s2 is "\\"
The second type of string(s) are called "verbatim" strings.
I have a string:
" a.1.2.3 #4567 "
and I want to reduce that to just "1.2.3".
Currently using Substring() and Remove(), but that breaks if there ends up being more numbers after the pound sign.
What's the best way to go about doing this? I've read a bunch of questions on regex & string.split, but I can't get anything I try to work in VB.net. Would I have to do a match then replace using the match result?
Any help would be much appreciated.
This should work:
string input = " a.1.2.3 #4567 ";
int poundIndex = input.IndexOf("#");
if(poundIndex >= 0)
{
string relevantPart = input.Substring(0, poundIndex).Trim();
IEnumerable<Char> numPart = relevantPart.SkipWhile(c => !Char.IsDigit(c));
string result = new string(numPart.ToArray());
}
Demo
Try this...
String[] splited = split("#");
String output = splited[0].subString(2); // 1 is the index of the "." after "a" considering there are no blank spaces before it..
Here is regex way of doing it
string input = " a.1.2.3 #4567 ";
Regex regex = new Regex(#"(\d\.)+\d");
var match = regex.Match(input);
if(match.Success)
{
string output = match.Groups[0].Value;//"1.2.3"
//Or
string output = match.Value;//"1.2.3"
}
If the pound sign is the most relevant bit, rely on Split. Sample VB.NET code:
Dim inputString As String = " a.1.2.3 #4567 "
If (inputString.Contains("#")) Then
Dim firstBit As String = inputString.Split("#")(0).Trim()
Dim headingToRemove As String = "a."
Dim result As String = firstBit.Substring(headingToRemove.Length, firstBit.Length - headingToRemove.Length)
End If
As far as this is a multi-language question, here comes the translation to C#:
string inputString = " a.1.2.3 #4567 ";
if (inputString.Contains("#"))
{
string firstBit = inputString.Split('#')[0].Trim();
string headingToRemove = "a.";
string result = firstBit.Substring(headingToRemove.Length, firstBit.Length - headingToRemove.Length);
}
I guess another way using unrolled
\d+ (?: \. \d+ )+
what is the efficient mechanism to remove 2 or more white spaces from a string leaving single white space.
I mean if string is "a____b" the output must be "a_b".
You can use a regular expression to replace multiple spaces:
s = Regex.Replace(s, " {2,}", " ");
Something like below maybe:
var b=a.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
var noMultipleSpaces = string.Join(" ",b);
string tempo = "this is a string with spaces";
RegexOptions options = RegexOptions.None;
Regex regex = new Regex(#"[ ]{2,}", options);
tempo = regex.Replace(tempo, #" ");
You Can user this method n pass your string value as argument
you have to add one namespace also using System.Text.RegularExpressions;
public static string RemoveMultipleWhiteSpace(string str)
{
// A.
// Create the Regex.
Regex r = new Regex(#"\s+");
// B.
// Remove multiple spaces.
string s3 = r.Replace(str, #" ");
return s3;
}
How to remove whitespaces between characters in c#?
Trim() can be used to remove the empty spaces at the beginning of the string as well as at the end. For example " C Sharp ".Trim() results "C Sharp".
But how to make the string into CSharp? We can remove the space using a for or a for each loop along with a temporary variable. But is there any built in method in C#(.Net framework 3.5) to do this like Trim()?
You could use String.Replace method
string str = "C Sharp";
str = str.Replace(" ", "");
or if you want to remove all whitespace characters (space, tabs, line breaks...)
string str = "C Sharp";
str = Regex.Replace(str, #"\s", "");
If you want to keep one space between every word. You can do it this way as well:
string.Join(" ", inputText.Split(new char[0], StringSplitOptions.RemoveEmptyEntries).ToList().Select(x => x.Trim()));
Use String.Replace to replace all white space with nothing.
eg
string newString = myString.Replace(" ", "");
if you want to remove all spaces in one word:
input.Trim().Replace(" ","")
And If you want to remove extra spaces in the sentence, you should use below:
input.Trim().Replace(" +","")
the regex " +", would check if there is one ore more following space characters in the text and replace them with one space.
If you want to keep one space between every word. this should do it..
public static string TrimSpacesBetweenString(string s)
{
var mystring =s.RemoveTandNs().Split(new string[] {" "}, StringSplitOptions.None);
string result = string.Empty;
foreach (var mstr in mystring)
{
var ss = mstr.Trim();
if (!string.IsNullOrEmpty(ss))
{
result = result + ss+" ";
}
}
return result.Trim();
}
it will remove the string in between the string
so if the input is
var s ="c sharp";
result will be "c sharp";
//Remove spaces from a string just using substring method and a for loop
static void Main(string[] args)
{
string businessName;
string newBusinessName = "";
int i;
Write("Enter a business name >>> ");
businessName = ReadLine();
for(i = 0; i < businessName.Length; i++)
{
if (businessName.Substring(i, 1) != " ")
{
newBusinessName += businessName.Substring(i, 1);
}
}
WriteLine("A cool web site name could be www.{0}.com", newBusinessName);
}
var str=" c sharp "; str = str.Trim();
str = Regex.Replace(str, #"\s+", " "); ///"c sharp"
string myString = "C Sharp".Replace(" ", "");
I found this method great for doing things like building a class that utilizes a calculated property to take lets say a "productName" and stripping the whitespace out to create a URL that will equal an image that uses the productname with no spaces. For instance:
namespace XXX.Models
{
public class Product
{
public int ProductID { get; set; }
public string ProductName { get; set; }
public string ProductDescription { get; set; }
public string ProductImage
{
get { return ProductName.Replace(" ", string.Empty) + ".jpg"; }
}
}
}
So in this answer I have used a very similar method as w69rdy, but used it in an example, plus I used string.Empty instead of "". And although after .Net 2.0 there is no difference, I find it much easier to read and understand for others who might need to read my code. I also prefer this because I sometimes get lost in all the quotes I might have in a code block.