C# 字串切割

ex: 有一字串如下

abcdefg 1234

要切割成

s1 = abcdefg

s2 = 1234

要用什麼方法呢??

Update:

Bill Chung.....

如果中間的空白是不固定的, 那怎麼辦?? 謝謝~~

Update 2:

也就是縮, 我只要空白的左及右邊的字串就好, 謝謝~

2 Answers

Rating
  • 1 decade ago
    Favorite Answer

    String.Split 方法 ,因為中間有個分隔字元[你的例子是個空白]

    example:

    string mystring;

    mystring = "abcdefg 1234";

    string s1;

    string s2;

    s1 = mystring.Split(' ')[0];

    s2 = mystring.Split(' ')[1];

    MessageBox.Show(s1);

    MessageBox.Show(s2);

    2009-04-28 10:23:06 補充:

    那就把分出來是空白的移除

    string mystring;

    mystring = "abcdefg 1234";

    string[] s1;

    s1= mystring.Split(' ');

    int i;

    2009-04-28 10:23:19 補充:

    for (i = 0; i < s1.Length; i++)

    {

    if (s1[i].TrimStart(' ') != "")

    {

    MessageBox.Show(s1[i]);

    }

    }

    Source(s): MSDN
  • 1 decade ago

    #include <stdio.h>

    #include <stdlib.h>

    int main(void)

    {

    char str[200];

    int i=0,s=1;

    printf("輸入字串");

    gets(str);

    printf("S%d=",s);

    while(str[i]!=0)

    {

    printf("%c",str[i]);

    if(str[i]==' ')

    {

    printf("\nS%d=",s+1);

    s++;

    }

    i++;

    }

    system("pause");

    return 0;

    }

Still have questions? Get your answers by asking now.