简体   繁体   中英

How can I manage to split the int value in C#

For this int has the value of "19971998". I really wanted to split this value into like this "1997 - 1998"??

int index = Convert.ToInt32(radioListBox1.SelectedIndex);
string indexvalue = Convert.ToString(this.radioListBox1.Items[index]);
string input = Regex.Replace(indexvalue, "[^0-9]+", string.Empty);
MessageBox.Show(input);

you can write like:

int index = Convert.ToInt32(radioListBox1.SelectedIndex);
string indexvalue = Convert.ToString(this.radioListBox1.Items[index]);
string input = Regex.Replace(indexvalue, ".{4}", "$0-");
MessageBox.Show(input);
var s = "19971998";
String.Format("{0}-{1}", s.Substring(0,4), s.Substring(4, 4)));

To make it work with Regex you'd need to do the following:

string input = Regex.Replace(indexvalue, "^(.{4})", "$1-");

But as someone suggested, it may be even easier to do this one.

string input = indexvalue.Insert(4, "-");
    int index = Convert.ToInt32(radioListBox1.SelectedIndex);
    string indexvalue = Convert.ToString(this.radioListBox1.Items[index]);
    string input = Regex.Replace(indexvalue, "[^0-9]+", string.Empty);

The problem was solved, this was missing my code.

    if (input.Length == 8) input = input.Insert(4, " - ");

    MessageBox.Show(input);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM