how can I get a substring of everything before dot or comma?
For example:
string input = "2.1";
int charLocation = text.IndexOf(".", StringComparison.Ordinal);
string test = input.Substring(0, charLocation );
but what if I have an input = "2,1" ?
I would like to do it in one method, not using twice a substring (once for dot and once for comma)?
string test = input.Split(new Char[] { ',', '.' })[0];
This will split the string for either comma or period...
input.Split(',','.');
Use the IndexOfAny function. It allows you to specify a list of characters to look for, rather than just a single character. You could then make a substring up to the return value of that function.
e.g.
char[] chars = { '.', ',' }
String out = s.Substring(0,s.IndexOfAny(chars));
Related
I've found many references to do similar to this but none seem to be exactly what I'm after, so hoping someone could help.
In simple terms, I want to take a string entered by a user (into a Winform input), and firstly strip out any blanks, then replace any of a list of 'illegal' characters with the UK currency symbol (£). The requirement is for the input to be used but the file that is generated by the process has the modified filename.
I wrote a function (based on an extension method) but it's not working quite as expected:
public static class ExtensionMethods
{
public static string Replace(this string s, char[] separators, string newVal)
{
var temp = s.Split(separators, StringSplitOptions.RemoveEmptyEntries);
return String.Join(newVal, temp);
}
}
public static string RemoveUnwantedChars(string enteredName, char[] unwanted, string rChar)
{
return enteredName.Replace(unwanted, rChar);
}
Which in my code, I've called twice:
char[] blank = { ' ' };
string ename = Utilities.RemoveUnwantedChars(this.txtTableName.Text, blank, string.Empty);
char[] unwanted = { '(', ')', '.', '%', '/', '&', '+' };
string fname = Utilities.RemoveUnwantedChars(ename, unwanted, "£");
If I enter a string that contains at least one space, all of the characters above and some other letters (for example, " (GH) F16.5% M X/Y&1+1"), I get the following results:
ename = "(GH)F16.5%MX/Y&1+1" - this is correct in that it has removed the blanks.
fname = "GH£F16£5£MX£Y£1£1" - this hasn't worked correctly in that it has not replaced the first character but removed it.
The rest of the characters have been correctly replaced. It only occurs when one of the 'illegal' characters is at the start of the string - if my string was "G(H) F16.5% M X/Y&1+1", I would correctly get "G£H£F16£5£MX£Y£1£1". It also replaces multiple 'illegal' characters with one '£', so "M()GX+.1" would become "M£GX£1" but should be "M££GX££1".
I think the problem is in your Replace extension. You are splitting in this line
var temp = s.Split(separators, StringSplitOptions.RemoveEmptyEntries);
You are removing empty entries causing the unexpected result. Use this instead:
var temp = s.Split(separators, StringSplitOptions.None);
The problem is occuring because string.Join() only puts separators between substrings - it will never put one at the start.
One possible solution is to avoid using string.Join() and write Replace() like this instead:
public static class ExtensionMethods
{
public static string Replace(this string s, char[] separators, string newVal)
{
var sb = new StringBuilder(s);
foreach (char ch in separators)
{
string target = new string(ch, 1);
sb.Replace(target, newVal);
}
return sb.ToString();
}
}
When you use split method in your Replace function you get following strings:
GH, F16, 5, MX, Y, 1, 1.
When you join them with your newVal you get:
GH + newVal + F16 + newVal + ... thus omitting first replaced character.
You would probably need some special case to check if first char is "illegal" and put newVal at start of your string.
I have this string
"1.3.1.\tProduction and Sales Analysis:"
I want to trim numbers and escape sequences from the start and end of string.
Output Should be :
"Production and Sales Analysis:"
My code :
Char[] trimArray = new Char[] {'0','1','2','3','4','5','6','7','8','9','.',',',':','\\','/'};
String test = "1.3.1.\tProduction and Sales Analysis:";
test = test.TrimEnd(trimArray);
but problem is when a string like 23232-232123-asd-323 comes it also removes the digits
I want to remove the unwanted characters from start and end of string But Want to keep the string like 23232-232123-asd-323 or mobile numbers
Thanks.
Is there always '\t' in the middle?
You can try to split by '\t' and trim end.
Split(new char[]{'\t'});
If colon is always at the end of what you want to get you can split again ;)
If there is something in common separating the bad number and the good numbers like say "t", then how about finding the index of the common letter/symbol then creating a substring of everything after. For example:
String test = "1.3.1.\tProduction and Sales Analysis:";
index = test.LastIndexOfAny(new char[] { 't' });
test = test.Substring(index +1);
This should give you "Production and Sales Analysis:". You could do the same for the ":" except you want everything before it like so
int index = test.LastIndexOfAny(new char[] { ':' });
test = test.Substring(0, index);
With regex:
using System.Text.RegularExpressions;
string input = "1.3.1.\tProduction and Sales Analysis:";
string rgx = #"(?:[0-9.]+)*(?:\\[a-zA-Z])*([\w\s\.\:-_]+)(?:\\[a-zA-Z])*";
string result = Regex.Match(input, rgx).Groups[1].Value.TrimStart();
I am using c# and i have a string like
-Xyz
--Xyz
---Xyz
-Xyz-Abc
--Xyz-Abc
i simply want to remove any leading special character until alphabet comes , Note: Special characters in the middle of string will remain same . What is the fastest way to do this?
You could use string.TrimStart and pass in the characters you want to remove:
var result = yourString.TrimStart('-', '_');
However, this is only a good idea if the number of special characters you want to remove is well-known and small.
If that's not the case, you can use regular expressions:
var result = Regex.Replace(yourString, "^[^A-Za-z0-9]*", "");
I prefer this two methods:
List<string> strings = new List<string>()
{
"-Xyz",
"--Xyz",
"---Xyz",
"-Xyz-Abc",
"--Xyz-Abc"
};
foreach (var s in strings)
{
string temp;
// String.Trim Method
char[] charsToTrim = { '*', ' ', '\'', '-', '_' }; // Add more
temp = s.TrimStart(charsToTrim);
Console.WriteLine(temp);
// Enumerable.SkipWhile Method
// Char.IsPunctuation Method (se also Char.IsLetter, Char.IsLetterOrDigit, etc.)
temp = new String(s.SkipWhile(x => Char.IsPunctuation(x)).ToArray());
Console.WriteLine(temp);
}
How would I get the directory and filename from the following string using C#:
string test = "test#test.com, snap555.jpg, c:\users\test\desktop\snap555.jpg";
I only want to be able to get the "c:\users\test\desktop\snap555.jpg" from the string and turn it into another string.
The characters before the "," will always be different and different lengths such as: "bob#bob.com, x.txt, c:\users\test\desktop\x.txt"
What is the easiest way to do this in c#?
Thanks.
t
If the comma delimiter does not appear in the first part, you can use:
string pathName = test.Split(',')[2];
If that space after the comma is a problem and assuming that the first part never has spaces, you can use:
char[] delims = new char[] { ',', ' '};
string pathName = test.Split(delims, StringSplitOptions.RemoveEmptyEntries)[2];
This example assumes you always want the third item, as mentioned in your question. Otherwise, change the 2 in the examples above to the correct index of the item you want. For example, if it should always be the last item, you can do:
char[] delims = new char[] { ',', ' '};
string[] items = test.Split(delims, StringSplitOptions.RemoveEmptyEntries);
string pathName = items[items.Length-1];
If there's always going to be a comma there you can use
string test = "snap555.jpg, c:\users\test\desktop\snap555.jpg";
string[] parts = test.Split(',');
Then get whatever you need from the parts array.
I have textbox in c#, contains two or three strings with white spaces. i want to store those strings seperately.please, suggest me any code. thanx.
var complexValue = #"asdfasdfsdf asdfasd fffff
asdfasdfasdf";
var complexValues = complexValue.Split();
NOTICE:
.Split() is a pseudo-overload, as it gets compiled as .Split(new char[0]).
additionally msdn tells us:
If the separator parameter is
null or contains
no characters, white-space characters
are assumed to be the delimiters.
White-space characters are defined by
the Unicode standard and return true
if they are passed to the
Char.IsWhiteSpace method.
Firstly use this name space
using System.Text.RegularExpressions;
in your code
string Message = "hi i am fine";
string []Record=Regex.Split(Message.Trim(), " ");
Output is an array.
I hope it works.
string[] parts = myTextbox.Text.Split();
Calling String.Split() with no parameters will force the method to consume all whitespace and only return the separated strings:
var individualStrings = originalString.Split();
To get three different strings in an array, you can use String.Split()
string[] myStringArray = OriginalString.Split(" ".ToCharArray());
string[] words = Regex.Split(textBox.Text, #"\s+");
Try this:
string str = #"this is my string";
string[] arr = str.Split(new char[] { char.Parse(" ") });
Try :
string data = TextBox1.Text;
var s1 = data.Split();
string a = s1[0].ToString();
string b= s1[1].ToString();