C # string manipulation

I have a string of 9 letters.

string myString = "123987898"; 

I want to get the first 3 letters "123", then 2 more letters "98", and then 4 more letters "7898".

Which C # string function supports this functionality.

+7
string c #
source share
3 answers

You can use Substring :

 myString.Substring(0,3) myString.Substring(3,2) myString.Substring(5,4) 

It is also possible to make it more complex than necessary with a combination of regular expressions and LINQ:

 string myString = "123987898"; Regex regex = new Regex("(.{3})(.{2})(.{4})"); string[] bits = regex .Match(myString) .Groups .Cast<Group>() .Skip(1) .Select(match => match.Value) .ToArray(); 
+19
source share

There is nothing built in, but it is easy enough to make yourself.

 public static IEnumerable<string> SplitBySize(string value, IEnumerable<int> sizes) { if (value == null) throw new ArgumentNullException("value"); if (sizes == null) throw new ArgumentNullException("sizes"); var length = value.Length; var currentIndex = 0; foreach (var size in sizes) { var nextIndex = currentIndex + size; if (nextIndex > length) { throw new ArgumentException("The sum of the sizes specified is larger than the length of the value specified.", "sizes"); } yield return value.Substring(currentIndex, size); currentIndex = nextIndex; } } 

Usage example

 foreach (var item in SplitBySize("1234567890", new[] { 2, 3, 5 })) { Console.WriteLine(item); } Console.ReadKey(); 
+1
source share

The best and most reliable way to handle this is to use regex

 public Regex MyRegex = new Regex (
       "(? \\ d {3}) (? \\ d {2}) (? \\ d {4})",
     RegexOptions.IgnoreCase
     |  RegexOptions.CultureInvariant
     |  RegexOptions.IgnorePatternWhitespace
     |  RegexOptions.Compiled
     );

You can then access them through the Groups property of the Match instance.

 Match m = MyRegex.Match ("123987898");
 if (m.Success) {
      int first3 = int.Parse (m.Groups ["first3"]. Value;
      int next2 = int.Parse (m.Groups ["next2"]. Value;
      int last4 = int.Parse (m.Groups ["last4"]. Value;

      / * Do whatever you have to do with first3, next2 and last 4!  * /
 }
0
source share

All Articles