How to split a string into individual letters - c#

I have a string that represent a number like 1234567890 and I want to split this into individual digits, somehow as follows:
<div class="counter">
#if (Model.Count > 0)
{
char[] num = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }
string TotalCount = #Model.Count;
string[] TheDigit = TotalCount.Split(num);
foreach (var TheDigit in TotalCount)
{
<li>TheDigit</li>
}
}
</div>
How can I achieve this properly? Anyway my output must be something like this:
<li>1</li><li>2</li>...<li>9</li><li class="Zero">0</li>

First of all this is not view logic, IMHO, so it should not be done in the view but in the controller. Opinions may vary on this.
To the point, if you need to obtain the digits of a number, you can do it arithmetically or string-wise. String-wise you could do (assuming that normal digits occupy only a character, culture info, bla bla, turkish I, bla):
var x = "1234567";
foreach(var digit in x)
{
<li>#digit</li>
}

So you have a char[] which contains digits and you want following as result?
<li>1</li><li>2</li>...<li>9</li>
You could use...
string result = string.Concat(num.Select(c => string.Format("<li>{0}</li>", c)));

My bad: I forgot to convert to string. Anyway is working as follows:
<div>
#if (Model.Count > 0)
{
<ul class="counter clearfix">
#{
string str = Model.Count.ToString();
foreach (var TheDigit in str)
{
<li>#TheDigit</li>
}
}
</ul>
}
<div>
<span>Joburi</span>
</div>
</div>
Thank you guys

Related

How to remove a charlist from a string

How can I remove a specific list of chars from a string?
For example I have the string Multilanguage File07 and want to remove all vowels, spaces and numbers to get the string MltlnggFl.
Is there any shorter way than using a foreach loop?
string MyLongString = "Multilanguage File07";
string MyShortString = MyLongString;
char[] charlist = new char[17]
{ 'a', 'e', 'i', 'o', 'u',
'0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', '0', ' ' };
foreach (char letter in charlist)
{
MyShortString = MyShortString.Replace(letter.ToString(), "");
}
Use this code to replace a list of chars within a string:
using System.Text.RegularExpressions;
string MyLongString = "Multilanguage File07";
string MyShortString = Regex.Replace(MyLongString, "[aeiou0-9 ]", "");
Result:
Multilanguage File07 => MltlnggFl
Text from which some chars should be removed 12345 => Txtfrmwhchsmchrsshldbrmvd
Explanation of how it works:
The Regex Expression I use here, is a list of independend chars defined by the brackets []
=> [aeiou0-9 ]
The Regex.Replace() iterates through the whole string and looks at each character, if it will match one of the characters within the Regular Expression.
Every matched letter will be replaced by an empty string ("").
How about this:
var charList = new HashSet<char>(“aeiou0123456789 “);
MyLongString = new string(MyLongString.Where(c => !charList.Contains(c)).ToArray());
Try this pattern: (?|([aeyuio0-9 ]+)). Replace it with empty string and you will get your desird result.
I used branch reset (?|...) so all characters are captured into one group for easier manipulation.
Demo.
public void removeVowels()
{
string str = "MultilanguAge File07";
var chr = str.Where(c => !"aeiouAEIOU0-9 ".Contains(c)).ToList();
Console.WriteLine(string.Join("", chr));
}
1st line: creating desire string variable.
2nd line: using linq ignore vowels words [captital case,lower case, 0-9 number & space] and convert into list.
3rd line: combine chr list into one line string with the help of string.join function.
result: MltlnggFl7
Note: removeVowels function not only small case, 1-9 number and empty space but also remove capital case word from string.

Lexicographically Sort String Array

I've been working on a challenge and have researched it for several hours and am still having trouble how to "properly" sort a string array or list of string in lexicographical order in C#.
The problem of the challenge I'm working:
Take into account only the lower case letters of two strings.
Compare them to find out which characters occur in both strings.
Compare those characters and find out which of the original strings contains the most occurrences of each character.
Append the result as a string in a format that depicts which string has the higher count "1:" or "2:" or if equal "=:" followed by all the characters in that string joined by "/".
Sort the result in decreasing order of their length, and when they are of equal lengths sort the substrings in ascending lexicographic order.
An example of the result is and below it is my output:
"2:eeeee/2:yy/=:hh/=:rr"
"2:eeeee/2:yy/=:rr/=:hh"
Another example of a correct result is and below it is my output:
1:ooo/1:uuu/2:sss/=:nnn/1:ii/2:aa/2:dd/2:ee/=:gg
=:nnn/1:ooo/1:uuu/2:sss/=:gg/1:ii/2:aa/2:dd/2:ee
The line of code that is causing this is:
strings = strings.OrderByDescending(x => x.Length).ThenBy(c => c).ToArray();
I've tried different ways of approaching this problem such as splitting the string into individual string arrays of certain lengths, perform a lexicographic order, then append them back into the result. But with the many different test cases, one would pass and the other would fail.
My issue is finding out why C# sees "=" as LESS THAN digits, when really it's greater on the ASCII chart. I ran a test and that is what String.Compare gave me. In Python, it gave me something different.
Here is my complete code, feel free to point out any bugs. I've only been programming for 9 months. I am aware it isn't the best solution.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
string s1 = "looping is fun but dangerous";
string s2 = "less dangerous than coding";
// Expected
Console.WriteLine("1:ooo/1:uuu/2:sss/=:nnn/1:ii/2:aa/2:dd/2:ee/=:gg\n");
// Result
Console.WriteLine(StringsMix(s1, s2));
}
public static string StringsMix(string s1, string s2)
{
StringBuilder sb = new StringBuilder();
// Convert string to char arrays order by ascending
char[] s1Chars = s1.Where(x => char.IsLower(x)).OrderBy(x => x).ToArray();
char[] s2Chars = s2.Where(x => char.IsLower(x)).OrderBy(x => x).ToArray();
// Insert arrays to find characters that appear in both
char[] inter = s1Chars.Intersect(s2Chars).ToArray();
for (int i = 0; i < inter.Length; i++){
// For each character, put all occurences in their respective array
// Get count
char[] s1Ch = s1.Where(x => x.Equals(inter[i])).ToArray();
char[] s2Ch = s2.Where(x => x.Equals(inter[i])).ToArray();
int s1Count = s1Ch.Length;
int s2Count = s2Ch.Length;
if (s1Count > s2Count)
{
string chars = new String(s1Ch);
sb.Append("1:" + chars + "/");
}
else if (s2Count > s1Count)
{
string chars = new String(s2Ch);
sb.Append("2:" + chars + "/");
}
else if (s1Count == s2Count)
{
string chars = new String(s1Ch);
sb.Append("=:" + chars + "/");
}
}
string final = String.Empty;
string[] strings = sb.ToString().Split('/');
strings = strings.OrderByDescending(x => x.Length).ThenBy(c => c).ToArray(); // "Lexicographical ordering"
final = String.Join("/", strings);
strings = final.Split('/').Where(x => x.Length > 3).Select(x => x).ToArray(); // Remove trailing single characters
final = String.Join("/", strings);
return final;
}
}
}
This happens because '=' sorts before '1' and '2'; you want it to sort after the digits.
You can force this order by adding a special condition in the middle:
var specialOrder = "12=";
var ordered = data
.OrderByDescending(s => s.Length)
.ThenBy(s => specialOrder.IndexOf(s[0])) // <<== Add this
.ThenBy(s => s);
This will ensure that the initial character sorts according to the order of characters in specialOrder string, i.e. '1', then '2', then '='.
Demo.
Note: The code makes an assumption that the sequence has no empty strings. Your code ensures that each string has at least three characters, so it is not a problem.

split string to three doubles

I used C# and I would like split text comprised 3 doubles seperated by commas and spaces.
I did:
double[] doubles = mystr.Trim().Split(new char[] { ' ', ',' })
.Select(s => Convert.ToDouble(s))
.ToArray();
when mystr = 33,44,55 for example it works fine (numbers seperated by only one comma)
Also, when mystr= 33 44 55 for example it works fine (numbers seperated by only one space)
BUT, when mystr= 33, 44, 55 it doesn't works (one space after the comma between each two numbers)
It also doesn't work when mystr = 33 44 55 (two spaces between each two numbers)
In both above examples I got an unhandled exception.
How can I solve it?
Thanks!
You can add an option to remove empty entries in the Split:
var array = Array.ConvertAll(mystr.Split(new [] { ' ', ',' },
StringSplitOptions.RemoveEmptyEntries),
Convert.ToDouble);
You could use System.Text.RegularExpressions.Regex:
var pattern = #"(\d+)((,\s*|\s+)|$)";
const int RegexTimeoutSeconds = 1;
var matches = Regex.Matches(mystr, pattern, RegexOptions.None, TimeSpan.FromSeconds(RegexTimeoutSeconds));
var doubles = new List<double>();
foreach (Match match in matches)
{
var group = match.Groups[1];
var d = Convert.ToDouble(group.Value);
doubles.Add(d);
}
Just try specifying StringSplitOptions, and use StringSplitOptions.RemoveEmptyEntries to remove empty strings..
double[] doubles = mystr.Trim().Split(new char[] { ' ', ',' },StringSplitOptions.RemoveEmptyEntries)
.Select(Convert.ToDouble)
.ToArray();

c# format a string of characters so letters before number are capital and after are lowercase

I'm trying to format a string in c# and i m not sure if i shoudl be using regex or something like that basically if a modelname is md234GH and Dgh321Hh They need to be MD234gh and DGH321hh.
So capitals numbers lowercase
I tried doing the following:
TextInfo textInfo = new CultureInfo("en-GB", false).TextInfo;
foreach (var product in products)
{
if (product.ModelName != null)
{
product.ModelName = product.ModelName.ToLower();
product.ModelName = textInfo.ToTitleCase(product.ModelName);
}
}
but this only makes the first letter capital.
Any advice appreciated
ToTitleCase is only mean to make the first letter of each word upper case. To do what you want, you'll need to split the string up and call .ToUpper and .ToLower as appropriate, e.g.:
Regex modelExpression = new Regex("^([A-Za-z]+)([0-9]+)([A-Za-z]+)$");
// Inside for loop...
Match m = modelExpression.Match(product.ModelName);
if (m.Success)
{
product.ModelName = m.Groups[1].Value.ToUpper()
+ m.Groups[2].Value
+ m.Groups[3].Value.ToLower();
}
You could use a regex:
(?i)^([a-z]+)(\d+)([a-z]+)$
In a replace, something like:
model = Regex.Replace(model, #"(?i)^([a-z]+)(\d+)([a-z]+)$", delegate(Match m)
{
return m.Groups[1].Value.ToUpper() + m.Groups[2].Value + m.Groups[3].Value.ToLower();
});
ToTitleCase will only make the first letter of each word upper case.
You need to use ToUpper to make all letters upper case.
There is nothing built in to do what you want, so you will need to make your own - parsing the string between the numerals and formatting each part.
A regular expression looks like the best bet:
^([A-Za-z]+)([0-9]+)([A-Za-z]+)$
Usage:
var formatted = Regex.Replace(originalString,
#"^([A-Za-z]+)([0-9]+)([A-Za-z]+)$",
m => m.Groups[1].Value.ToUpper() +
m.Groups[2].Value +
m.Groups[3].Value.ToLower());
The result for "md234GH" is "MD234gh" and for "Dgh321Hh" it is "DGH321hh".
using System.Text.RegularExpressions;
Match m=Regex.Match("md234GH","(\\w+?)(\\d+)(\\w+)");
Console.WriteLine("{0}{1}{2}",m.Groups[1].Value.ToUpper(),m.Groups[2].Value,m.Groups[3].Value.ToLower());
Regexes are a good match for this:
\b(\D+)(\d+)(\D+)\b
Now all that is needed is to use the regex api in C# and give it a delegate that does the replace. I've used a lambda as the delegate:
var result = Regex.Replace("md234GH", #"\b(\D+)(\d+)(\D+)\b", x =>
x.Groups[1].Value.ToUpper()
+ x.Groups[2].Value
+ x.Groups[3].Value.ToUpper()
);
Here is a solution in plain C. This assumes 8-bit ASCII or ANSI character set is used.
void convertModelName(char *name)
{
char *ptr;
int lcase = 0;
for (ptr=name; *ptr; ptr++) {
if (*ptr >= '0' && *ptr <= '9') {
lcase = 1;
} else {
if (lcase) {
*ptr |= 0x20;
} else {
*ptr &= 0xdf;
}
}
}
}

remove the any character from string except number,dot(.), and comma(,) [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
remove the invalid character from price
Hi friends,
i have a scenario where i have to remove the invalid character from price using c# code.
i want the regular ex to remove the character or some thing good then this.
For Ex- my price is
"3,950,000 ( Ex. TAX )"
i want to remove "( Ex. TAX )" from the price.
my scenario is that. i have to remove the any character from string except number,dot(.), and comma(,)
please help..
thanks in advance
Shivi
private string RemoveExtraText(string value)
{
var allowedChars = "01234567890.,";
return new string(value.Where(c => allowedChars.Contains(c)).ToArray());
}
string s = #"3,950,000 ( Ex. TAX )";
string result = string.Empty;
foreach (var c in s)
{
int ascii = (int)c;
if ((ascii >= 48 && ascii <= 57) || ascii == 44 || ascii == 46)
result += c;
}
Console.Write(result);
Notice that the dot in "Ex. TAX" will stay
How about this:
using System.Text.RegularExpressions;
public static Regex regex = new Regex(
"(\\d|[,\\.])*",
RegexOptions.IgnoreCase
| RegexOptions.CultureInvariant
| RegexOptions.IgnorePatternWhitespace
| RegexOptions.Compiled
);
//// Capture the first Match, if any, in the InputText
Match m = regex.Match(InputText);
//// Capture all Matches in the InputText
MatchCollection ms = regex.Matches(InputText);
//// Test to see if there is a match in the InputText
bool IsMatch = regex.IsMatch(InputText);
You can use LINQ
HashSet<char> validChars = new HashSet<char>(
new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ',', '.' });
var washedString = new string((from c in "3,950,000 ( Ex. TAX )"
where validChars.Contains(c)
select c).ToArray());
but the "." in "Ex. TAX" will remain.
you may use something like [^alpha] ore [^a-z]

Categories