如何从一个字符串分隔一个数字 [英] how to separate a number from a string
问题描述
其实我需要处理的情况怎么样
Actually I need to handle situation like
我应该给输入作为行< N>
应该有行和数字之间的间隔< N>
或任何单个非数字字符。
I should be giving input as rows <n>
There should be space between 'rows' and number <n>
or any single non numeric character.
我应该能够该字符串分出一部分,并把它分配给一个char变量和数字部分为INT ...
I should be able to separate that string part and assign it to a char variable and number part to a int...
的字符串部分应然后验证其是否正确的命令,或者如果输入如ADA AAD 99或adaha 9或adfad9..它应该说,其错误的命令一个错误的命令不..
The string part should be then verified whether its a correct command or not.. If a wrong command is entered like "ada aad 99" or "adaha 9" or "adfad9".. It should say "its wrong command".
我试图用的strtok()
,但不能处理字符串那里没有 NULL
在字符串之间。我试着使用$ 的sscanf(字符串,%s%* C%D,STR,试验#);
但它甚至没有工作了所有的可能性。
I tried to use strtok()
, but it can't handle strings where there isn't NULL
in between strings.. I tried to use $ sscanf(string,"%s %*c %d",str, &num);
but its even not working for all possibilities.
我该怎么办呢?
推荐答案
我没有看到 strtok的
您的问题,这将是在这种情况下,我认为完美的。
I don't see your problem with strtok
, it would be perfect in this case I think.
在伪code:
line = getline();
split_line_into_tokens(line);
if tokens[0] == "command1" {
if tokens_num > 2 {
error("to many arguments to command1");
} else if tokens_num < 2 {
error("command1 needs one argument");
} else {
do_command_1(tokens[1]);
}
} else {
error("unknown command");
}
在上面的伪code, split_line_into_tokens()
使用 strtok的
以创建数组<青霉>令牌的,使用空间作为分隔符。如果 strtok的
返回一个空字符串(不是 NULL
)再有就是使用一个以上的空间,你跳过。在 split_line_into_tokens
创建标记
数组,其中第一项包含命令,其余包含的参数。变量 tokens_num
设置为令牌的阵列中的数
In the above pseudo-code, split_line_into_tokens()
uses strtok
to create an array of tokens, using space as the separator. If strtok
returns an empty string (not NULL
) then there is more than one space used and you skip that. The split_line_into_tokens
creates the tokens
array, which first entry contains the command, and the remaining contains the arguments. The variable tokens_num
is set to the number of tokens in the array.
这篇关于如何从一个字符串分隔一个数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!