манипуляция строкой c # - PullRequest
7 голосов
/ 11 марта 2010

У меня есть строка из 9 букв.

string myString = "123987898";

Я хочу получить первые 3 буквы "123" тогда еще 2 буквы "98" а затем еще 4 буквы "7898".

Какая функция c # string поддерживает эту функцию.

Ответы [ 3 ]

19 голосов
/ 11 марта 2010

Вы можете использовать Подстрока :

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

Также возможно сделать его более сложным, чем необходимо, используя комбинацию регулярных выражений и 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();
1 голос
/ 11 марта 2010

Нет ничего встроенного, но это достаточно легко сделать самостоятельно.

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;
    }
}

Пример использования

foreach (var item in SplitBySize("1234567890", new[] { 2, 3, 5 }))
{
    Console.WriteLine(item);
}
Console.ReadKey();
0 голосов
/ 11 марта 2010

Лучший и надежный способ справиться с этим - использовать регулярное выражение

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

Затем вы можете получить к ним доступ через свойство Groups экземпляра Match

.
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! */
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...