遍历字符串?

发布于 2024-11-08 14:05:13 字数 309 浏览 0 评论 0原文

不完全确定这是可能的,但假设我有两个像这样的字符串:

"IAmAString-00001"
"IAmAString-00023"

通过向上移动末尾数字的索引,从 IAmAString-0001 迭代到 IAmAString-00023 的快速简便方法是什么?

问题比这更普遍一些,例如,我可以处理的字符串可以是任何格式,但最后一堆字符始终是数字,因此像 Super_Confusing-String#w00t0003 这样的东西,在这种情况下,最后一个 0003 将是是我用来迭代的东西。

有什么想法吗?

Not entirely sure this is possible, but say I have two strings like so:

"IAmAString-00001"
"IAmAString-00023"

What would be a quick'n'easy way to iterate from IAmAString-0001 to IAmAString-00023 by moving up the index of just the numbers on the end?

The problem is a bit more general than that, for example the string I could be dealing could be of any format but the last bunch of chars will always be numbers, so something like Super_Confusing-String#w00t0003 and in that case the last 0003 would be what I'd use to iterate through.

Any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

你没皮卡萌 2024-11-15 14:05:13

您可以使用 char.IsDigit:

    static void Main(string[] args)
    {
        var s = "IAmAString-00001";
        int index = -1;
        for (int i = 0; i < s.Length; i++)
        {
            if (char.IsDigit(s[i]))
            {
                index = i;
                break;
            }
        }
        if (index == -1)
            Console.WriteLine("digits not found");
        else
            Console.WriteLine("digits: {0}", s.Substring(index));
    }

生成以下输出:

digits: 00001

You can use char.IsDigit:

    static void Main(string[] args)
    {
        var s = "IAmAString-00001";
        int index = -1;
        for (int i = 0; i < s.Length; i++)
        {
            if (char.IsDigit(s[i]))
            {
                index = i;
                break;
            }
        }
        if (index == -1)
            Console.WriteLine("digits not found");
        else
            Console.WriteLine("digits: {0}", s.Substring(index));
    }

which produces this output:

digits: 00001
娇妻 2024-11-15 14:05:13

string.Format 和 for 循环应该做你想要的。

for(int i = 0; i <=23; i++)
{
    string.Format("IAmAString-{0:D4}",i);
}

或类似的东西(不在编译器前面)。

string.Format and a for loop should do what you want.

for(int i = 0; i <=23; i++)
{
    string.Format("IAmAString-{0:D4}",i);
}

or something close to that (not sitting in front of a compiler).

爱,才寂寞 2024-11-15 14:05:13
string start = "IAmAString-00001";
string end = "IAmAString-00023";

// match constant part and ending digits
var matchstart = Regex.Match(start,@"^(.*?)(\d+)$");
int numberstart = int.Parse(matchstart.Groups[2].Value);

var matchend = Regex.Match(end,@"^(.*?)(\d+)$");
int numberend = int.Parse(matchend.Groups[2].Value);

// constant parts must be the same
if (matchstart.Groups[1].Value != matchend.Groups[1].Value)
    throw new ArgumentException("");

// create a format string with same number of digits as original
string format = new string('0', matchstart.Groups[2].Length);

for (int ii = numberstart; ii <= numberend; ++ii)
    Console.WriteLine(matchstart.Groups[1].Value + ii.ToString(format));
string start = "IAmAString-00001";
string end = "IAmAString-00023";

// match constant part and ending digits
var matchstart = Regex.Match(start,@"^(.*?)(\d+)$");
int numberstart = int.Parse(matchstart.Groups[2].Value);

var matchend = Regex.Match(end,@"^(.*?)(\d+)$");
int numberend = int.Parse(matchend.Groups[2].Value);

// constant parts must be the same
if (matchstart.Groups[1].Value != matchend.Groups[1].Value)
    throw new ArgumentException("");

// create a format string with same number of digits as original
string format = new string('0', matchstart.Groups[2].Length);

for (int ii = numberstart; ii <= numberend; ++ii)
    Console.WriteLine(matchstart.Groups[1].Value + ii.ToString(format));
棒棒糖 2024-11-15 14:05:13

您可以使用正则表达式:

var match=Regex.Match("Super_Confusing-String#w00t0003",@"(?<=(^.*\D)|^)\d+$");
if(match.Success)
{
    var val=int.Parse(match.Value);
    Console.WriteLine(val);
}

要更具体地回答,您可以使用命名组来提取您需要的内容:

var match=Regex.Match(
    "Super_Confusing-String#w00t0003",
    @"(?<prefix>(^.*\D)|^)(?<digits>\d+)$");

if(match.Success)
{
    var prefix=match.Groups["prefix"].Value;
    Console.WriteLine(prefix);
    var val=int.Parse(match.Groups["digits"].Value);
    Console.WriteLine(val);
}

You could use a Regex:

var match=Regex.Match("Super_Confusing-String#w00t0003",@"(?<=(^.*\D)|^)\d+$");
if(match.Success)
{
    var val=int.Parse(match.Value);
    Console.WriteLine(val);
}

To answer more specifically, you could use named groups to extract what you need:

var match=Regex.Match(
    "Super_Confusing-String#w00t0003",
    @"(?<prefix>(^.*\D)|^)(?<digits>\d+)$");

if(match.Success)
{
    var prefix=match.Groups["prefix"].Value;
    Console.WriteLine(prefix);
    var val=int.Parse(match.Groups["digits"].Value);
    Console.WriteLine(val);
}
笔落惊风雨 2024-11-15 14:05:13

如果您可以假设最后 5 个字符是数字,则:

string prefix = "myprefix-";
for (int i=1; i <=23; i++)
{
  Console.WriteLine(myPrefix+i.ToString("D5"));
}

If you can assume that the last 5 characters are the number then:

string prefix = "myprefix-";
for (int i=1; i <=23; i++)
{
  Console.WriteLine(myPrefix+i.ToString("D5"));
}
半夏半凉 2024-11-15 14:05:13

该函数将找到尾随号码。

private int FindTrailingNumber(string str)
{
    string numString = "";
    int numTest;
    for (int i = str.Length - 1; i > 0; i--)
    {
        char c = str[i];
        if (int.TryParse(c.ToString(), out numTest))
        {
            numString = c + numString;
        }
    }
    return int.Parse(numString);
}

假设所有基本字符串都相同,这将在字符串之间进行迭代。

string s1 = "asdf123";
string s2 = "asdf127";
int num1 = FindTrailingNumber(s1);
int num2 = FindTrailingNumber(s2);

string strBase = s1.Replace(num1.ToString(), "");

for (int i = num1; i <= num2; i++)
{
    Console.WriteLine(strBase + i.ToString());
}

This function will find the trailing number.

private int FindTrailingNumber(string str)
{
    string numString = "";
    int numTest;
    for (int i = str.Length - 1; i > 0; i--)
    {
        char c = str[i];
        if (int.TryParse(c.ToString(), out numTest))
        {
            numString = c + numString;
        }
    }
    return int.Parse(numString);
}

Assuming all your base strings are the same, this would iterate between strings.

string s1 = "asdf123";
string s2 = "asdf127";
int num1 = FindTrailingNumber(s1);
int num2 = FindTrailingNumber(s2);

string strBase = s1.Replace(num1.ToString(), "");

for (int i = num1; i <= num2; i++)
{
    Console.WriteLine(strBase + i.ToString());
}
┊风居住的梦幻卍 2024-11-15 14:05:13

我认为如果你从最后一次开始搜索会更好(里克已经给你投票了,因为这是你的逻辑:-))

static void Main(string[] args)
    {
        var s = "IAmAString-00001";
        int index = -1;
        for (int i = s.Length - 1; i >=0; i--)
        {
            if (!char.IsDigit(s[i]))
            {
                index = i;
                break;
            }
        }
        if (index == -1)
            Console.WriteLine("digits not found");
        else
            Console.WriteLine("digits: {0}", s.Substring(index));
        Console.ReadKey();
    }

HTH

I think it would be better if you do the search from the last (Rick already upvoted you since it was ur logic :-))

static void Main(string[] args)
    {
        var s = "IAmAString-00001";
        int index = -1;
        for (int i = s.Length - 1; i >=0; i--)
        {
            if (!char.IsDigit(s[i]))
            {
                index = i;
                break;
            }
        }
        if (index == -1)
            Console.WriteLine("digits not found");
        else
            Console.WriteLine("digits: {0}", s.Substring(index));
        Console.ReadKey();
    }

HTH

爱情眠于流年 2024-11-15 14:05:13

如果最后 X 个数字始终是数字,那么:

int x = 5;
string s = "IAmAString-00001";
int num = int.Parse(s.Substring(s.Length - x, x));
Console.WriteLine("Your Number is: {0}", num);

如果最后一个数字的长度可以是 3、4 或 5,那么您将需要更多的逻辑:

int x = 0;
string s = "IAmAString-00001";
foreach (char c in s.Reverse())//Use Reverse() so you start with digits only.
{
    if(char.IsDigit(c) == false)
        break;//If we start hitting non-digit characters, then exit the loop.
    ++x;
}
int num = int.Parse(s.Substring(s.Length - x, x));
Console.WriteLine("Your Number is: {0}", num);

我不擅长复杂的正则表达式。正因为如此,当不需要最大程度的优化时,我总是回避它。原因是 RegEx 并不总是按照您期望的方式解析字符串。如果有替代解决方案仍然可以快速运行,那么我宁愿走这条路,因为我更容易理解并知道它可以与任何字符串组合一起使用。

例如:如果您使用此处提供的一些其他解决方案以及“I2AmAString-000001”等字符串,那么您将得到“2000001”作为您的数字,而不是“1”。

If the last X numbers are always digits, then:

int x = 5;
string s = "IAmAString-00001";
int num = int.Parse(s.Substring(s.Length - x, x));
Console.WriteLine("Your Number is: {0}", num);

If the last digits can be 3, 4, or 5 in length, then you will need a little more logic:

int x = 0;
string s = "IAmAString-00001";
foreach (char c in s.Reverse())//Use Reverse() so you start with digits only.
{
    if(char.IsDigit(c) == false)
        break;//If we start hitting non-digit characters, then exit the loop.
    ++x;
}
int num = int.Parse(s.Substring(s.Length - x, x));
Console.WriteLine("Your Number is: {0}", num);

I'm not good with complicated RegEx. Because of this, I always shy away from it when maximum optimization is unnecessary. The reason for this is RegEx doesn't always parse strings the way you expect it to. If there is and alternate solution that will still run fast then I'd rather go that route as it's easier for me to understand and know that it will work with any combination of strings.

For Example: if you use some of the other solutions presented here with a string like "I2AmAString-000001", then you will get "2000001" as your number instead of "1".

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文