Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
97 views
in Technique[技术] by (71.8m points)

c# - How can I turning that number of string?

public static void Main(string[] args)
{
    Console.WriteLine("Enter string: ");
    string st= Console.ReadLine();
    Console.WriteLine(Alpha(st));
}
public static string Alpha(string str)
{
    int[] nums = new int[str.Length / 2]; // 4 5 2 
    string num = "";
    string nw = "";
    string harfler = " ";
    string[] harflerr = new string[str.Length / 2]; // A B C
     
    for(int i = 0; i < str.Length; i += 2)
    {
        harfler += str[i].ToString();
    }
    for(int i = 1; i < str.Length; i+=2)
    {
        num += str[i].ToString();
    }
    for(int i = 0; i < num.Length; i++)
    {
        nums[i] += num[i];
    }
    for(int i = 0; i < harflerr.Length; i++)
    {
        harflerr[i] += harfler[i];
    }
    for(int i = 0; i < harflerr.Length; i++)
    {
       for(int j = 0; j < nums[i]; j++)
        {
            nw += harflerr[i];
        }
    }

    return nw;
}

Output must be like:

"A4B5C2" ? "AAAABBBBBCC"

"C2F1E5" ? "CCFEEEEE"

"T4S2V2" ? "TTTTSSVV"

"A1B2C3D4" ? "ABBCCCDDDD"

Why doesn't nums [i] // for example return as many as 4 // in the nums [i] part.

question from:https://stackoverflow.com/questions/65861056/how-can-i-turning-that-number-of-string

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I would suggest using regular expression for this because of two reasons. First is that what happens when user input something like A12B7 or A1BC4? Your approach will fail because you're assuming that every letter will have only one digit following it. Second reason is pure readability. It's easier to filter everything out using regular expressions than doing it by hand, character by character.


So first define your regex like this one: (?'pair'[A-Za-z]{1}d{0,})

Having this expression will retrieve pairs that have letter and possibly a number following. Then you can iterate through all of the pairs and just create new string for each.

string result = "";
foreach(string pair in pairs)
{
    char character = pair[0];
    int length = 1;
    if (pair.Length > 1)
    {
        length = int.Parse(pair.Substring(1));
    }
    result += new String(character, length);
}
Console.WriteLine(result);

You can test this online on rextester


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...