C# Splitting a string [duplicate] - c#

This question already has answers here:
Splitting a string into chunks of a certain size
(39 answers)
Closed 8 years ago.
I've got a problem. I have a string "3d8sAdTd6c" And I would need it to split it, so the conclusion would be:
3d
8s
Ad
Td
6c
If you could tell me how to do this I would be very grateful.

Perhaps:
string[] result = str
.Select((c, index ) => new{ c, index })
.GroupBy(x => x.index / 2)
.Select(xg => string.Join("", xg.Select(x => x.c)))
.ToArray();
This groups every second character and uses string.Join to concat them to a string.

Something like below should work with loops.
string str = "3d8sAdTd6c";
string newstr = "";
int size = 2;
int stringLength = str.Length;
for (int i = 0; i < stringLength ; i += size)
{
if (i + size > stringLength) size = stringLength - i;
newstr = newstr + str.Substring(i, size) + "\r\n";
}
Console.WriteLine(newstr);

string input = "3d8sAdTd6c";
for (int i = 0; i < input.Length; i+=2) {
Console.WriteLine(input.Substring(i,2));
}

To split any string into pairs of two characters:
/// <summary>
/// Split a string into pairs of two characters.
/// </summary>
/// <param name="str">The string to split.</param>
/// <returns>An enumerable sequence of pairs of characters.</returns>
/// <remarks>
/// When the length of the string is not a multiple of two,
/// the final character is returned on its own.
/// </remarks>
public static IEnumerable<string> SplitIntoPairs(string str)
{
if (str == null) throw new ArgumentNullException("str");
int i = 0;
for (; i + 1 < str.Length; i += 2)
{
yield return str.Substring(i, 2);
}
if (i < str.Length)
yield return str.Substring(str.Length - 1);
}
Usage:
var pairs = SplitIntoPairs("3d8sAdTd6c");
Result:
3d
8s
Ad
Td
6c

Related

How to reverse a string 2character and 2character from the end c#

Sample string:
A3148579
Expected result:
798514A3
I tried this code:
public static string Reverse(string s)
{
char[] charArray = s.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
the actual result is 9758413A
but I want 798514A3
thanks everyone
You can try below code. This is just to give you a idea and you can update based on the test cases and requirement. Below code works fine for your input which you have mentioned. I have not considered if the length is odd. You can do your research and update logic which will help you to learn and know more.
string input = "A3148579";
Stack stack = new Stack();
int count = 0;
string output = "";
for (int i = 0; i < input.Length/2; i++)
{
stack.Push(input.Substring(count, 2));
count = count + 2;
}
while (stack.Count > 0)
{
output += stack.Pop().ToString();
}
You can split the initial string into chunks of size = 2 (e.g. with a help of Substring); note that ToCharArray() returns chars i.e. chunks of size = 1.
Let's generalize the solution: now we have size of chunks
Code:
using System.Linq;
...
public static string Reverse(string s, int size = 2) {
if (size < 1)
throw new ArgumentOutOfRangeException(nameof(size));
if (string.IsNullOrEmpty(s))
return s;
int n = s.Length / size + (s.Length % size == 0 ? 0 : 1);
return string.Concat(Enumerable
.Range(0, n)
.Select(i => i < n - 1 ? s.Substring(i * size, size) : s.Substring(i * size))
.Reverse());
}
Demo:
Console.Write(Reverse("A3148579"));
Outcome:
798514A3
C# Example: Split An Array into Multiple Smaller Arrays
Use Lambda expression to extends Array class to include a new method called Split:
public static class MyArrayExtensions
{
/// <summary>
/// Splits an array into several smaller arrays.
/// </summary>
/// <typeparam name="T">The type of the array.</typeparam>
/// <param name="array">The array to split.</param>
/// <param name="size">The size of the smaller arrays.</param>
/// <returns>An array containing smaller arrays.</returns>
public static IEnumerable<IEnumerable<T>> Split<T>(this T[] array, int size)
{
for (var i = 0; i < (float)array.Length / size; i++)
{
yield return array.Skip(i * size).Take(size);
}
}
}
Test the new array class method:
[TestMethod]
public void TestSplit2()
{
string str = "A3148579";
char[] array1 = new char[str.Length];
for (int i = 0; i < array1.Length; i++)
{
array1[i] = i;
}
// Split into smaller arrays of maximal 2 elements
IEnumerable<IEnumerable<int>> splited = array1.Split<int>(2);
int j = 0;
foreach (IEnumerable<int> s in splited){
j++;
}
log.InfoFormat("Splitted in to {0} smaller arrays.", j);
}
Finally you just need to reverse the resulted array(smaller).

Finding the longest word (and write it out) in string without split, distinct and foreach [duplicate]

This question already has answers here:
Finding longest word in string
(4 answers)
Closed 3 years ago.
I got an assignment to make a method to find the longest word in a string without split, distinct and foreach.
I was able to split the words and count the length but I am stuck on how can I actually compare and write them out.
static void Main(string[] args)
{
String s1 = "Alex has 2 hands.";
longestWord(s1);
Console.
}
static void longestWord(String s1)
{
char emp = ' ';
int count = 0;
char[] ee = s1.ToCharArray();
for (int i = 0; i < ee.Length; i++)
{
if (ee[i] == emp || ee[i] == '.')
{
count++;
Console.Write(" " + (count-1));
Console.WriteLine();
count = 0;
}
else
{
Console.Write(ee[i]);
count++;
}
}
}
The output right now looks like this:
Alex 4
has 3
2 1
hands 5
I am pretty sure I would be able to get only the longest number to show by comparing count before reset with temp int but how to write out the word with it.
Or if there is a easier way which probably is.
You are already on a good way. Instead of directly printing the words, store the length and position of the longest word and print it at the end. Like so:
static void longestWord(String s1)
{
char emp = ' ';
int longestLength = 0;
int longestStart = 0;
int currentStart = 0;
for (int i = 0; i < s1.Length; i++)
{
if (s1[i] == emp || s1[i] == '.')
{
// calculate the current word length
int currentLength = i - currentStart;
// test if this is longer than the currently longest
if(currentLength > longestLength)
{
longestLength = currentLength;
longestStart = currentStart;
}
// a new word starts at the next character
currentStart = i + 1;
}
}
// print the longest word
Console.WriteLine($"Longest word has length {longestLength}: \"{s1.Substring(longestStart, longestLength)}\"");
}
There is no need for the .ToCharArray(). You can access the string directly.
I will question whether you are actually supposed to treat "2" as a word and count it at all. Using regular expressions will allow you to approach the problem using a LINQ one-liner:
static void Main(string[] args)
{
String s1 = "Alex has 2 hands.";
var word = longestWord(s1);
Console.WriteLine(word);
//Console.ReadLine();
}
static string longestWord(string s1) {
return Regex.Matches(s1,"[A-Za-z]+") // find all sequences containing alphabetical characters, you can add numberas as well: [A-Za-z0-9]
.Cast<Match>() // cast results to Enumberable<Match> so we can apply LINQ to it
.OrderByDescending(m => m.Length) // luckily for us, Match comes with Length, so we just sort our results by it
.Select(m => m.Value) // instead of picking up everything, we only want the actual word
.First(); // since we ordered by descending - first item will be the longest word
}
You can store for every word the chars in new list of chars (list for dynamic length)
and if the new word is longer of the prev long word convert it to string.
If you have two word in same length it will take the first.
If you want the last change the "maxLength < count" to "maxLength <= count"
static string longestWord(String s1)
{
char emp = ' ';
int count = 0;
int maxLength = 0;
string maxWord = string.Empty;
List<char> newWord = new List<char>();
char[] ee = s1.ToCharArray();
for (int i = 0; i < ee.Length; i++)
{
if (ee[i] == emp || ee[i] == '.')
{
if (maxLength < count)
{
maxLength = count;
maxWord = new string(newWord.ToArray());
}
count = 0;
newWord = new List<char>();
}
else
{
newWord.Add(ee[i]);
count++;
}
}
return maxWord;
}

Get index of nth occurrence of char in a string

I'm trying to make a function that returns the index of the Nth occurrence of a given char in a string.
Here is my attempt:
private int IndexOfNth(string str, char c, int n)
{
int index = str.IndexOf(c) + 1;
if (index >= 0)
{
string temp = str.Substring(index, str.Length - index);
for (int j = 1; j < n; j++)
{
index = temp.IndexOf(c) + 1;
if (index < 0)
{
return -1;
}
temp = temp.Substring(index, temp.Length - index);
}
index = index + (str.Length);
}
return index;
}
This should find the first occurrence, chop off that front part of the string, find the first occurrence from the new substring, and on and on until it gets the index of the nth occurrence. However I failed to consider how the index of the final substring is going to be offset from the original actual index in the original string. How do I make this work?
Also as a side question, if I want the char to be the tab character do I pass this function '\t' or what?
Don't do that; IndexOf takes a second parameter that specifies where to start.
private static int IndexOfNth(string str, char c, int n) {
int s = -1;
for (int i = 0; i < n; i++) {
s = str.IndexOf(c, s + 1);
if (s == -1) break;
}
return s;
}
Taking all these substrings seems pretty wasteful to me. Why not just loop yourself?
private int IndexOfNth(string str, char c, int n)
{
int remaining = n;
for (int i = 0; i < str.Length; i++)
{
if (str[i] == c)
{
remaining--;
if (remaining == 0)
{
return i;
}
}
}
return -1;
}
(I considered using IndexOf in a loop like minitech's solution, but decided it was a bit fiddly. Either's fine, of course. Both basically do the same work, only ever checking each character once. Using IndexOf may be slightly more efficient, but go for whichever you find more readable.)
Using LINQ to find the index of the 5'th a in the string aababaababa:
var str = "aababaababa";
var ch = 'a';
var n = 5;
var result = str
.Select((c, i) => new { c, i })
.Where(x => x.c == ch)
.Skip(n - 1)
.FirstOrDefault();
return result != null ? result.i : -1;
I tend to first think about how to access the collection using Linq.
// 0-based n.
char result = str
.Where(x => x == c)
.Skip(n)
.FirstOrDefault();
Then I'll unpack the linq and add the indexed iteration.
int foundCount = -1;
for(int position = 0; position < str.Length; position++)
{
char x = str[position];
if (x == c)
{
foundCount += 1;
// 0-based n
if (foundCount == n)
{
return position;
}
}
}
return -1;
Then I think about: what if this method returned all the indexes so I can query them:
public IEnumerable<int> IndexesOf(string str, char c)
{
for(int position = 0; position < str.Length; position++)
{
char x = str[position];
if (x == c)
{
yield return position;
}
}
}
Called by:
int position = IndexesOf(str, c)
.Skip(n) // 0-based n
.DefaultIfEmpty(-1)
.First();
Instead of creating a bunch of substrings, why not use the IndexOf overload that takes a starting index? This will be both easier (you won't have to adjust the final index) and more efficient (you don't have to allocate a bunch of substrings).
Not tested but something like this should work:
private int IndexOfNth(string str, char c, int n)
{
int index = -1;
while (n-- > 0)
{
index = str.IndexOf(c, index + 1);
if (index == -1) break;
}
return index;
}
Hadn't seen anyone use the CharEnumerator yet...
public Int32 getNthIndex(string str, char c, Int32 n)
{
Int32 index = 0;
Int32 count = 0;
if (str != null && str.Length > 0 && !(n < 1))
{
CharEnumerator scanner = str.GetEnumerator();
while (scanner.MoveNext())
{
if (scanner.Current == c) { count++; }
if (count == n) { break; }
index++;
}
if (count < n) { index = -1; }
}
if (count == 0) { return -1; } else { return index; }
}
Should be pretty efficient, no substrings or anything, just scan through the string you're given and keep count.
You could use the following method which will return the nth occurrence of the specified character within the designated string.
public static int IndexOfNthCharacter(string str, int n, char c) {
int index = -1;
if (!str.Contains(c.ToString()) || (str.Split(c).Length-1 < n)) {
return -1;
}
else {
for (int i = 0; i < str.Length; i++) {
if (n > 0) {
index++;
}
else {
return index;
}
if (str[i] == c) {
n--;
}
}
return index;
}
}
Note that if the character you are searching for does not exist within the string you are searching or the the occurrence number you are searching for is greater than what exists in the string then this method will return -1.
First of all, I'd make it an extension method. This way, you can skip the otherwise obligatory null check and also just call it on a string like you would do with IndexOf, IndexOfAny etc.
Then I'd make two methods of this. One to retrieve all indexes (IndexesOf, that might come handy at sometime) and the other one (IndexOfNth) uses the first function to check for the nth index:
using System;
using System.Collections.Generic; // # Necessary for IList<int>
using System.Linq; // # Necessary for IList<int>.ToArray()
/// <summary>
/// Returns all indexes of the specified <paramref name="value"/> in the current string.
/// </summary>
/// <param name="#this">The current string this method is operating on.</param>
/// <param name="value">The value to be searched.</param>
/// <returns><c>Null</c>, if <paramref name="value"/> is <c>null</c> or empty.
/// An array holding all indexes of <paramref name="value"/> in this string,
/// else.</returns>
static int[] IndexesOf(this string #this, string value)
{
// # Can't search for null or string.Empty, you can return what
// suits you best
if (string.IsNullOrEmpty(value))
return null;
// # Using a list instead of an array saves us statements to resize the
// array by ourselves
IList<int> indexes = new List<int>();
int startIndex = 0;
while (startIndex < #this.Length)
{
startIndex = #this.IndexOf(value, startIndex);
if (startIndex >= 0)
{
// # Add the found index to the result and increment it by length of value
// afterwards to keep searching AFTER the current position
indexes.Add(startIndex);
startIndex += value.Length;
}
else
{
// # Exit loop, if value does not occur in the remaining string
break;
}
}
// # Return an array to conform with other string operations.
return indexes.ToArray();
}
/// <summary>
/// Returns the indexes of the <paramref name="n"/>th occurrence of the specified
/// <paramref name="value"/> in the current string.
/// </summary>
/// <param name="#this">The current string this method is operating on.</param>
/// <param name="value">The value to be searched.</param>
/// <param name="n">The 1-based nth occurrence.</param>
/// <returns><c>-1</c>, if <paramref name="value"/> is <c>null</c> or empty -or-
/// <paramref name="n"/> is less than 1.</returns>
static int IndexOfNth(this string #this, string value, int n /* n is 1-based */)
{
// # You could throw an ArgumentException as well, if n is less than 1
if (string.IsNullOrEmpty(value) || n < 1)
return -1;
int[] indexes = #this.IndexesOf(value);
// # If there are n or more occurrences of 'value' in '#this'
// return the nth index.
if (indexes != null && indexes.Length >= n)
{
return indexes[n - 1];
}
return -1;
}
You can overload these using char value instead of string value in the signature and calling their respective counterparts passing value.ToString(). Et voilá!
Surely, these methods can be refactored, e.g. using LINQ, make IndexesOf recursive etc.

Find string permutation including the single character using C# or F#

I would like to generate a list of all possible permutations of a string containing a variable list of characters.
For example if I have the string "ABC", I would like to have a list that contains all the possible variations, like: A, B, C, AB, BC.
Thank you.
It's hard to tell exactly what you want, but based on your example output here's how to do what I think you're after in F#.
let combinations (s:string) =
let rec loop acc i =
seq {
for i in i .. (s.Length - 1) do
let acc = acc + s.[i..i]
yield acc
yield! loop acc (i + 1)
}
loop "" 0
combinations "ABC" |> Seq.toList //["A"; "AB"; "ABC"; "AC"; "B"; "BC"; "C"]
Here's a LINQ version:
Func<string, IEnumerable<string>> perm = t =>
{
Func<string, string, IEnumerable<string>> perm2 = null;
perm2 =
(t0, t1s) =>
from n in Enumerable.Range(0, t1s.Length)
let c = t1s.Substring(n, 1)
let x = t1s.Remove(n, 1)
let h = t0 + c
from r in (new [] { h, }).Concat(perm2(h, x))
select r;
return perm2("", t);
};
Use it like this:
var ps = perm("abc");
And it will perform a lazy computation.
var ps = perm("abcdefghijklmnopqrstuvwxyz").Take(2);
// Only computes two values when executed
Here will return all of the permutations (not distinct) given a string of chars. it's not fast or efficient, but it does work...
public List<string> permute(string value, string prefix = "")
{
List<string> result = new List<string>();
for (int x=0;x<value.Length;x++)
{
result.Add(prefix + value[x]);
result.AddRange(permute( value.Remove(x, 1), prefix + value[x]));
}
return result;
}
To use:
List<string> output = permute("abc");
Check out this snippet at F# Snippets
If you are looking for a permutation by index (instead of having to iterate over all the permutations) you can use a numbering system called factoradics (Source) to find them. Here is the code from the original article, with a stronger C# style (the original code is very 'C++ish') and generics.
/// <summary>
/// Permutes the specified atoms; in lexicographical order.
/// </summary>
/// <typeparam name="T">The type of elements.</typeparam>
/// <param name="atoms">The atoms.</param>
/// <param name="index">The index of the permutation to find.</param>
/// <returns>The permutation.</returns>
public static IList<T> Permute<T>(this IList<T> atoms, int index)
{
var result = new T[atoms.Count];
Permute(atoms, result, index);
return result;
}
/// <summary>
/// Permutes the specified atoms; in lexicographical order.
/// </summary>
/// <typeparam name="T">The type of elements.</typeparam>
/// <param name="atoms">The atoms.</param>
/// <param name="target">The array to place the permutation in.</param>
/// <param name="index">The index of the permutation to find.</param>
public static void Permute<T>(this IList<T> atoms, IList<T> target, int index)
{
if (atoms == null)
throw new ArgumentNullException("atoms");
if (target == null)
throw new ArgumentNullException("target");
if (target.Count < atoms.Count)
throw new ArgumentOutOfRangeException("target");
if (index < 0)
throw new ArgumentOutOfRangeException("index");
var order = atoms.Count;
// Step #1 - Find factoradic of k
var perm = new int[order];
for (var j = 1; j <= order; j++)
{
perm[order - j] = index % j;
index /= j;
}
// Step #2 - Convert factoradic[] to numeric permuatation in perm[]
var temp = new int[order];
for (var i = 0; i < order; i++)
{
temp[i] = perm[i] + 1;
perm[i] = 0;
}
perm[order - 1] = 1; // right-most value is set to 1.
for (var i = order - 2; i >= 0; i--)
{
perm[i] = temp[i];
for (var j = i + 1; j < order; j++)
{
if (perm[j] >= perm[i])
perm[j]++;
}
}
// Step #3 - map numeric permutation to string permutation
for (var i = 0; i < order; ++i)
{
target[i] = atoms[perm[i] - 1];
}
}

Splitting a string / number every Nth Character / Number?

I need to split a number into even parts for example:
32427237 needs to become 324 272 37
103092501 needs to become 103 092 501
How does one go about splitting it and handling odd number situations such as a split resulting in these parts e.g. 123 456 789 0?
If you have to do that in many places in your code you can create a fancy extension method:
static class StringExtensions {
public static IEnumerable<String> SplitInParts(this String s, Int32 partLength) {
if (s == null)
throw new ArgumentNullException(nameof(s));
if (partLength <= 0)
throw new ArgumentException("Part length has to be positive.", nameof(partLength));
for (var i = 0; i < s.Length; i += partLength)
yield return s.Substring(i, Math.Min(partLength, s.Length - i));
}
}
You can then use it like this:
var parts = "32427237".SplitInParts(3);
Console.WriteLine(String.Join(" ", parts));
The output is 324 272 37 as desired.
When you split the string into parts new strings are allocated even though these substrings already exist in the original string. Normally, you shouldn't be too concerned about these allocations but using modern C# you can avoid this by altering the extension method slightly to use "spans":
public static IEnumerable<ReadOnlyMemory<char>> SplitInParts(this String s, Int32 partLength)
{
if (s == null)
throw new ArgumentNullException(nameof(s));
if (partLength <= 0)
throw new ArgumentException("Part length has to be positive.", nameof(partLength));
for (var i = 0; i < s.Length; i += partLength)
yield return s.AsMemory().Slice(i, Math.Min(partLength, s.Length - i));
}
The return type is changed to public static IEnumerable<ReadOnlyMemory<char>> and the substrings are created by calling Slice on the source which doesn't allocate.
Notice that if you at some point have to convert ReadOnlyMemory<char> to string for use in an API a new string has to be allocated. Fortunately, there exists many .NET Core APIs that uses ReadOnlyMemory<char> in addition to string so the allocation can be avoided.
You could use a simple for loop to insert blanks at every n-th position:
string input = "12345678";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < input.Length; i++)
{
if (i % 3 == 0)
sb.Append(' ');
sb.Append(input[i]);
}
string formatted = sb.ToString();
One very simple way to do this (not the most efficient, but then not orders of magnitude slower than the most efficient).
public static List<string> GetChunks(string value, int chunkSize)
{
List<string> triplets = new List<string>();
while (value.Length > chunkSize)
{
triplets.Add(value.Substring(0, chunkSize));
value = value.Substring(chunkSize);
}
if (value != "")
triplets.Add(value);
return triplets;
}
Heres an alternate
public static List<string> GetChunkss(string value, int chunkSize)
{
List<string> triplets = new List<string>();
for(int i = 0; i < value.Length; i += chunkSize)
if(i + chunkSize > value.Length)
triplets.Add(value.Substring(i));
else
triplets.Add(value.Substring(i, chunkSize));
return triplets;
}
This is half a decade late but:
int n = 3;
string originalString = "32427237";
string splitString = string.Join(string.Empty,originalString.Select((x, i) => i > 0 && i % n == 0 ? string.Format(" {0}", x) : x.ToString()));
LINQ rules:
var input = "1234567890";
var partSize = 3;
var output = input.ToCharArray()
.BufferWithCount(partSize)
.Select(c => new String(c.ToArray()));
UPDATED:
string input = "1234567890";
double partSize = 3;
int k = 0;
var output = input
.ToLookup(c => Math.Floor(k++ / partSize))
.Select(e => new String(e.ToArray()));
If you know that the whole string's length is exactly divisible by the part size, then use:
var whole = "32427237!";
var partSize = 3;
var parts = Enumerable.Range(0, whole.Length / partSize)
.Select(i => whole.Substring(i * partSize, partSize));
But if there's a possibility the whole string may have a fractional chunk at the end, you need to little more sophistication:
var whole = "32427237";
var partSize = 3;
var parts = Enumerable.Range(0, (whole.Length + partSize - 1) / partSize)
.Select(i => whole.Substring(i * partSize, Math.Min(whole.Length - i * partSize, partSize)));
In these examples, parts will be an IEnumerable, but you can add .ToArray() or .ToList() at the end in case you want a string[] or List<string> value.
The splitting method:
public static IEnumerable<string> SplitInGroups(this string original, int size) {
var p = 0;
var l = original.Length;
while (l - p > size) {
yield return original.Substring(p, size);
p += size;
}
yield return original.Substring(p);
}
To join back as a string, delimited by spaces:
var joined = String.Join(" ", myNumber.SplitInGroups(3).ToArray());
Edit: I like Martin Liversage solution better :)
Edit 2: Fixed a bug.
Edit 3: Added code to join the string back.
I would do something like this, although I'm sure there are other ways. Should perform pretty well.
public static string Format(string number, int batchSize, string separator)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i <= number.Length / batchSize; i++)
{
if (i > 0) sb.Append(separator);
int currentIndex = i * batchSize;
sb.Append(number.Substring(currentIndex,
Math.Min(batchSize, number.Length - currentIndex)));
}
return sb.ToString();
}
I like this cause its cool, albeit not super efficient:
var n = 3;
var split = "12345678900"
.Select((c, i) => new { letter = c, group = i / n })
.GroupBy(l => l.group, l => l.letter)
.Select(g => string.Join("", g))
.ToList();
Try this:
Regex.Split(num.toString(), "(?<=^(.{8})+)");
A nice implementation using answers from other StackOverflow questions:
"32427237"
.AsChunks(3)
.Select(vc => new String(vc))
.ToCsv(" "); // "324 272 37"
"103092501"
.AsChunks(3)
.Select(vc => new String(vc))
.ToCsv(" "); // "103 092 501"
AsChunks(): https://stackoverflow.com/a/22452051/538763
ToCsv(): https://stackoverflow.com/a/45891332/538763
I went through all the comments and decided to build this extension method:
public static string FormatStringToSplitSequence(this string input, int splitIndex, string splitCharacter)
{
if (input == null)
return string.Empty;
if (splitIndex <= 0)
return string.Empty;
return string.Join(string.Empty, input.Select((x, i) => i > 0 && i % splitIndex == 0 ? string.Format(splitCharacter + "{0}", x) : x.ToString()));
}
Example:
var text = "24455";
var result = text.FormatStringToSplitSequence(2, ".");
Output: 24.45.5
This might be off topic as I don't know why you wish to format the numbers this way, so please just ignore this post if it's not relevant...
How an integer is shown differs across different cultures. You should do this in a local independent manner so it's easier to localize your changes at a later point.
int.ToString takes different parameters you can use to format for different cultures.
The "N" parameter gives you a standard format for culture specific grouping.
steve x string formatting is also a great resource.
For a dividing a string and returning a list of strings with a certain char number per place, here is my function:
public List<string> SplitStringEveryNth(string input, int chunkSize)
{
var output = new List<string>();
var flag = chunkSize;
var tempString = string.Empty;
var lenght = input.Length;
for (var i = 0; i < lenght; i++)
{
if (Int32.Equals(flag, 0))
{
output.Add(tempString);
tempString = string.Empty;
flag = chunkSize;
}
else
{
tempString += input[i];
flag--;
}
if ((input.Length - 1) == i && flag != 0)
{
tempString += input[i];
output.Add(tempString);
}
}
return output;
}
You can try something like this using Linq.
var str = "11223344";
var bucket = 2;
var count = (int)Math.Ceiling((double)str.Length / bucket);
Enumerable.Range(0, count)
.Select(_ => (_ * bucket))
.Select(_ => str.Substring(_, Math.Min(bucket, str.Length - _)))
.ToList()
You can also use the StringReader class to reads a block of characters from the input string and advances the character position by count.
StringReader Class Read(Char[], Int32, Int32)
The simplest way to separate thousands with a space, which actually looks bad, but works perfect, would be:
yourString.ToString("#,#").Replace(',', ' ');

Categories

Resources