C,215字节,196字节
@tucuxi节省了19个字节!
打高尔夫球:
char i[99],o[999],b[99],z[99];t,x,n,c;main(){gets(i);sscanf(i,"%s %[^[]s",b,z);while(sscanf(i+t,"%*[^0-9]%d%n",&x,&n)==1)sprintf(o,"%s[%d] = %d;\n",z,c++,x),t+=n;printf("%s %s[%d];\n%s",b,z,c,o);}
取消高尔夫:
/*
* Global strings:
* i: input string
* o: output string
* b: input array type
* z: input array name
*/
char i[ 99 ], o[ 999 ], b[ 99 ], z[ 99 ];
/* Global ints initialized to zeros */
t, x, n, c;
main()
{
/* Grab input string from stdin, store into i */
gets( i );
/* Grab the <type> <array_name> and store into b and z */
sscanf( i, "%s %[^[]s", b, z );
/* Grab only the int values and concatenate to output string */
while( sscanf( i + t, "%*[^0-9]%d%n", &x, &n ) == 1 )
{
/* Format the string and store into a */
sprintf( o, "%s[%d] = %d;\n", z, c++, x );
/* Get the current location of the pointer */
t += n;
}
/* Print the <type> <array_name>[<size>]; and output string */
printf( "%s %s[%d];\n%s", b, z, c, o );
}
链接:
http://ideone.com/h81XbI
说明:
要获取<type> <array_name>
,sscanf()
格式字符串是这样的:
%s A string delimited by a space
%[^[] The character set that contains anything but a `[` symbol
s A string of that character set
为了从字符串中提取int值int foo[] = {4, 8, 15, 16, 23, 42};
,我基本上使用以下函数将字符串标记化:
while( sscanf( i + t, "%*[^0-9]%d%n", &x, &n ) == 1 )
哪里:
i
是输入字符串(a char*
)
t
是指针位置的偏移量 i
x
是int
从字符串中实际解析出来的
n
是消耗的总字符,包括找到的数字
该sscanf()
格式字符串含义:
%* Ignore the following, which is..
[^0-9] ..anything that isn't a digit
%d Read and store the digit found
%n Store the number of characters consumed
如果将输入字符串可视化为char数组:
int foo[] = {4, 8, 15, 16, 23, 42};
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
00000000001111111111222222222233333
01234567890123456789012345678901234
并将int
4
其位于索引13,8
索引16等,这就是循环中每次运行的结果:
Run 1) String: "int foo[] = {4, 8, 15, 16, 23, 42};"
Starting string pointer: str[ 0 ]
Num chars consumed until after found digit: 14
Digit that was found: 4
Ending string pointer: str[ 14 ]
Run 2) String: ", 8, 15, 16, 23, 42};"
Starting string pointer: str[ 14 ]
Num chars consumed until after found digit: 3
Digit that was found: 8
Ending string pointer: str[ 17 ]
Run 3) String: ", 15, 16, 23, 42};"
Starting string pointer: str[ 17 ]
Num chars consumed until after found digit: 4
Digit that was found: 15
Ending string pointer: str[ 21 ]
Run 4) String: ", 16, 23, 42};"
Starting string pointer: str[ 21 ]
Num chars consumed until after found digit: 4
Digit that was found: 16
Ending string pointer: str[ 25 ]
Run 5) String: ", 23, 42};"
Starting string pointer: str[ 25 ]
Num chars consumed until after found digit: 4
Digit that was found: 23
Ending string pointer: str[ 29 ]
Run 6) String: ", 42};"
Starting string pointer: str[ 29 ]
Num chars consumed until after found digit: 4
Digit that was found: 42
Ending string pointer: str[ 33 ]
foo[0]=1;
可以接受吗?