Get non numeric values from string value c# - c#

I have value like below
string value = "11,.Ad23";
int n;
bool isNumeric = int.TryParse(value, out n);
I control if string is numeric or not.If string is not numeric and has non numeric i need to get non numeric values as below
Result must be as below
,.Ad
How can i do this in c# ?

If it doesn't matter if the non-digits are consecutive, it's simple:
string nonNumericValue = string.Concat(value.Where(c => !Char.IsDigit(c)));
Online Demo: http://ideone.com/croMht
If you use .NET 3.5. as mentioned in the comment there was no overload of String.Concat (or String.Join as in Dmytris answer) that takes an IEnumerable<string>, so you need to create an array:
string nonNumericValue = string.Concat(value.Where(c => !Char.IsDigit(c)).ToArray());
That takes all non-digits. If you instead want to take the middle part, so skip the digits, then take all until the the next digits:
string nonNumericValue = string.Concat(value.SkipWhile(Char.IsDigit)
.TakeWhile(c => !Char.IsDigit(c)));

Regular expression solution (glue together all non-numeric values):
String source = "11,.Ad23";
String result = String.Join("", Regex
.Matches(source, #"\D{1}")
.OfType<Match>()
.Select(item => item.Value));
Edit: it seems that you use and old version of .Net, in that case you can use straightforward code without RegEx, Linq etc:
String source = "11,.Ad23";
StringBuilder sb = new StringBuilder(source.Length);
foreach (Char ch in source)
if (!Char.IsDigit(ch))
sb.Append(ch);
String result = sb.ToString();

Although I like the solution proposed I think a more efficent way would be using regular expressions such as
[^\D]
Which called as
var regex = new Regex(#"[^\D]");
var nonNumeric = regex.Replace("11,.Ad23", ""));
Which returns:
,.Ad

Would a LINQ solution work for you?
string value = "11,.Ad23";
var result = new string(value.Where(x => !char.IsDigit(x)).ToArray());

Related

C# Char Array remove at specific index

Not to sure the best way to remove the char from the char array if the char at a given index is a number.
private string TextBox_CharacterCheck(string tocheckTextBox)
{
char[] charlist = tocheckTextBox.ToCharArray();
foreach (char character in charlist)
{
if (char.IsNumber(character))
{
}
}
return (new string(charlist));
}
Thanks in advance.
// this is now resolved. thank you to all who contributed
You could use the power of Linq:
return new string(tocheckTextBox.Where(c => !char.IsNumber(c)).ToArray())
This is fairly easy using Regex:
var result = Regex.Replace("a1b2c3d4", #"\d", "");
(as #Adassko notes, you can use "[0-9]" instead of #"\d" if you just want the digits 0 to 9, and not any other numeric characters).
You can also do it fairly efficiently using a StringBuilder:
var sb = new StringBuilder();
foreach (var ch in "a1b2c3d4")
{
if (!char.IsNumber(ch))
{
sb.Append(ch);
}
}
var result = sb.ToString();
You can also do it with linq:
var result = new string("a1b2c3d4".Where(x => !char.IsNumber(x)).ToArray());
Use Regex:
private string TextBox_CharacterCheck(string tocheckTextBox)
{
return Regex.Replace(tocheckTextBox, #"[\d]", string.Empty);;
}
System.String is immutable. You could use string.Replace or a regular expression to remove unwanted characters into a new string.
your best bet is to use regular expressions.
strings are immutable meaning that you can't change them - you need to rewrite the whole string - to do it in optimal way you should use StringBuilder class and Append every character that you want.
Also watch out for your code - char.IsNumber checks not only for characters 0-9, it also returns true for every numeric character such as ٢ and you probably don't want that.
here's the full list of characters returning true:
0123456789٠١٢٣٤٥٦٧٨٩۰۱۲۳۴۵۶۷۸۹߀߁߂߃߄߅߆߇߈߉०१२३४५६७८९০১২৩৪৫৬৭৮৯੦੧੨੩੪੫੬੭੮੯૦૧૨૩૪૫૬૭૮૯୦୧୨୩୪୫୬୭୮୯௦௧௨௩௪௫௬௭௮௯౦౧౨౩౪౫౬౭౮౯೦೧೨೩೪೫೬೭೮೯൦൧൨൩൪൫൬൭൮൯๐๑๒๓๔๕๖๗๘๙໐໑໒໓໔໕໖໗໘໙༠༡༢༣༤༥༦༧༨༩၀၁၂၃၄၅၆၇၈၉႐႑႒႓႔႕႖႗႘႙០១២៣៤៥៦៧៨៩᠐᠑᠒᠓᠔᠕᠖᠗᠘᠙᥆᥇᥈᥉᥊᥋᥌᥍᥎᥏᧐᧑᧒᧓᧔᧕᧖᧗᧘᧙᭐᭑᭒᭓᭔᭕᭖᭗᭘᭙᮰᮱᮲᮳᮴᮵᮶᮷᮸᮹᱀᱁᱂᱃᱄᱅᱆᱇᱈᱉᱐᱑᱒᱓᱔᱕᱖᱗᱘᱙꘠꘡꘢꘣꘤꘥꘦꘧꘨꘩꣐꣑꣒꣓꣔꣕꣖꣗꣘꣙꤀꤁꤂꤃꤄꤅꤆꤇꤈꤉꩐꩑꩒꩓꩔꩕꩖꩗꩘꩙0123456789
you should also use [0-9] rather than \d in your regular expressions if you want only parsable digits.
You can also use a trick to .Split your string on your character, then .Join it back. This not only allows you to remove one or more characters, it also lets you to replace it with some other character.
I use this trick to remove incorrect characters from file name:
string.Join("-", possiblyIncorrectFileName.Split(Path.GetInvalidFileNameChars()))
this code will replace any character that cannot be used in valid file name to -
You can use LINQ to remove the char from the char array if the char at a given index is a number.
CODE
//This will return you the list of char discarding the number.
var removedDigits = tocheckTextBox.Where(x => !char.IsDigit(x));
//This will return the string without numbers.
string output = string.join("", removedDigits);

Is there a better way to create acronym from upper letters in C#?

What is the best way to create acronym from upper letters in C#?
Example:
Alfa_BetaGameDelta_Epsilon
Expected result:
ABGDE
My solution works, but it's not nice
var classNameAbbreviationRegex = new Regex("[A-Z]+", RegexOptions.Compiled);
var matches = classNameAbbreviationRegex.Matches(enumTypeName);
var letters = new string[matches.Count];
for (var i = 0; i < matches.Count; i++)
{
letters[i] = matches[i].Value;
}
var abbreviation = string.Join(string.Empty, letters);
string.Join("", s.Where(char.IsUpper));
string.Join("", s.Where(x => char.IsUpper(x))
string test = "Alfa_BetaGameDelta_Epsilon";
string result = string.Concat(test.Where(char.IsUpper));
You can use the Where method to filter out the upper case characters, and the Char.IsUpper method can be used as a delegate directly without a lambda expression. You can create the resulting string from an array of characters:
string abbreviation = new String(enumTypeName.Where(Char.IsUpper).ToArray());
By using MORE regexes :-)
var ac = string.Join(string.Empty,
Regex.Match("Alfa_BetaGameDelta_Epsilon",
"(?:([A-Z]+)(?:[^A-Z]*))*")
.Groups[1]
.Captures
.Cast<Capture>()
.Select(p => p.Value));
More regexes are always the solution, expecially with LINQ! :-)
The regex puts all the [A-Z] in capture group 1 (because all the other () are non-capturing group (?:)) and "skips" all the non [A-Z] ([^A-Z]) by putting them in a non-capturing group. This is done 0-infinite times by the last *. Then a little LINQ to select the value of each capture .Select(p => p.Value) and the string.Join to join them.
Note that this isn't Unicode friendly... ÀÈÌÒÙ will be ignored. A better regex would use #"(?:(\p{Lu}+)(?:[^\p{Lu}]*))*" where \p{Lu} is the Unicode category UppercaseLetter.
(yes, this is useless... The other methods that use LINQ + IsUpper are better :-) but the whole example was built just to show the problems of Regexes with Unicode)
MUCH EASIER:
var ac = Regex.Replace("Alfa_BetaGameDelta_Epsilon", #"[^\p{Lu}]", string.Empty);
simply remove all the non-uppercase letters :-)
var str = "Alfa_BetaGammaDelta_Epsilon";
var abbreviation = string.Join(string.Empty, str.Where(c => c.IsUpper()));

Find an integer value inside a string

I'm looking to find the integer value inside the following string:
"value="5412304756756756756756792114343986"
How can I do this using C#?
You can use a regex to find the number in a string:
var resultString = Regex.Match(subjectString, #"\d+").Value;
For negative values:
var resultString = Regex.Match(yourString, #"(|-)\d+").Value;
You can look for the equals sign...
string yourString = "value=5412304756756756756756792114343986";
string integerPart = yourString.Split('=')[1];
You can use char.IsDigit
Something like .
string str = "value=5412304756756756756756792114343986";
List<char> justDigits = new List<char>();
foreach(char c in str)
{
if (char.IsDigit(c))
justDigits.Add(c);
}
string intValues = new string(justDigits.ToArray());
Or Shorter version
string intValues = new string(str.Where(char.IsDigit).ToArray());
You can use Regex:
int IntVal = Int32.Parse(Regex.Match(yourString, #"(|-)\d+").Value);
This will match negative numbers too. You could also iterate over every character in string and check id they are numerical but not really desirable solution because it can be a bottleneck.
Edit: In your input number is larger than long. For numbers like this, you can use BigInteger, from framework 4.0 onwards
Match match = new Regex("[0-9]+").Match("value=\"5412304756756756756756792114343986\"");
while(match.Success)
{
// Do something
match = match.NextMatch();
}

indexof exactvalue match

environment: microsoft visual studio 2008 c#
How do I get the index of a whole word found in a string
string dateStringsToValidate = "birthdatecake||birthdate||other||strings";
string testValue = "birthdate";
var result = dateStringsToValidate.IndexOf(testValue);
It doesn't have to be the way i did it either, for example, would it be better to use regular expressions or other methods?
Update:
The word is birthdate not birthdatecake. it doesn't have to retrieve the match but the index should find the right word. i don't think IndexOf is what i'm looking for then. Sorry for being unclear.
Use regular expressions for this
string dateStringsToValidate = "birthdatecake||birthdate||other||strings";
string testValue = "strings";
var result = WholeWordIndexOf(dateStringsToValidate, testValue);
// ...
public int WholeWordIndexOf(string source, string word, bool ignoreCase = false)
{
string testValue = "\\W?(" + word + ")\\W?";
var regex = new Regex(testValue, ignoreCase ?
RegexOptions.IgnoreCase :
RegexOptions.None);
var match = regex.Match(source);
return match.Captures.Count == 0 ? -1 : match.Groups[0].Index;
}
Learn more about regex options in c# here
Another option, depending on your needs, is to split the string (as I see you have some delimiters). Please note the index returned by the this option is the index by word count, not character count (In this case, 1, as C# has zero based arrays).
string dateStringsToValidate = "birthdatecake||birthdate||other||strings";
var split = dateStringsToValidate.Split(new string[] { "||" }, StringSplitOptions.RemoveEmptyEntries);
string testValue = "birthdate";
var result = split.ToList().IndexOf(testValue);
If you must deal with the exact index in the given string, then this is of little use to you. If you just want to find the best match in the string, this could work for you.
var dateStringsToValidate = "birthdatecake||birthdate||other||strings";
var toFind = "birthdate";
var splitDateStrings = dateStringsToValidate.Split(new[] {"||"}, StringSplitOptions.None);
var best = splitDateStrings
.Where(s => s.Contains(toFind))
.OrderBy(s => s.Length*1.0/toFind.Length) // a metric to define "best match"
.FirstOrDefault();
Console.WriteLine(best);

Regular expression to split string and number

I have a string of the form:
codename123
Is there a regular expression that can be used with Regex.Split() to split the alphabetic part and the numeric part into a two-element string array?
I know you asked for the Split method, but as an alternative you could use named capturing groups:
var numAlpha = new Regex("(?<Alpha>[a-zA-Z]*)(?<Numeric>[0-9]*)");
var match = numAlpha.Match("codename123");
var alpha = match.Groups["Alpha"].Value;
var num = match.Groups["Numeric"].Value;
splitArray = Regex.Split("codename123", #"(?<=\p{L})(?=\p{N})");
will split between a Unicode letter and a Unicode digit.
Regex is a little heavy handed for this, if your string is always of that form. You could use
"codename123".IndexOfAny(new char[] {'1','2','3','4','5','6','7','8','9','0'})
and two calls to Substring.
A little verbose, but
Regex.Split( "codename123", #"(?<=[a-zA-Z])(?=\d)" );
Can you be more specific about your requirements? Maybe a few other input examples.
IMO, it would be a lot easier to find matches, like:
Regex.Matches("codename123", #"[a-zA-Z]+|\d+")
.Cast<Match>()
.Select(m => m.Value)
.ToArray();
rather than to use Regex.Split.
Well, is a one-line only: Regex.Split("codename123", "^([a-z]+)");
Another simpler way is
string originalstring = "codename123";
string alphabets = string.empty;
string numbers = string.empty;
foreach (char item in mainstring)
{
if (Char.IsLetter(item))
alphabets += item;
if (Char.IsNumber(item))
numbers += item;
}
this code is written in java/logic should be same elsewhere
public String splitStringAndNumber(String string) {
String pattern = "(?<Alpha>[a-zA-Z]*)(?<Numeric>[0-9]*)";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(string);
if (m.find()) {
return (m.group(1) + " " + m.group(2));
}
return "";
}

Categories