读取用户输入并检查字符串 [英] Reading user input and checking the string

查看:67
本文介绍了读取用户输入并检查字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查C的子字符串的读入字符串?

How does one check the read in string for a substring in C?

如果我有以下内容

char name[21];
fgets(name, 21, stdin);

如何检查字符串中的一系列子字符串?

How do I check the string for a series of substrings?

如何检查字符前的子字符串?例如,如何检查=符号之前的子字符串?

How does one check for a substring before a character? For example, how would one check for a substring before an = sign?

推荐答案

警惕strtok();它不是可重入的.除其他外,这意味着如果您需要在一个函数中调用它,然后再调用另一个函数,并且如果另一个函数也使用strtok(),则您的第一个函数就搞砸了.它还在分隔符上写入NUL('\0')字节,因此它会随即修改输入字符串.如果要查找多个终止符,则无法确定找到了哪个终止符.此外,如果您编写一个库函数供其他人使用,但您的函数使用strtok(),则您必须记录这一事实,以使函数调用者不会因自己的代码失败而感到困惑调用函数后使用strtok().换句话说,它是有毒的.如果您的函数调用strtok(),通常会使您的函数不可重用;同样,使用strtok()的代码无法调用也使用该代码的其他人的函数.

Be wary of strtok(); it is not re-entrant. Amongst other things, it means that if you need to call it in one function, and then call another function, and if that other function also uses strtok(), your first function is messed up. It also writes NUL ('\0') bytes over the separators, so it modifies the input string as it goes. If you are looking for more than one terminator character, you can't tell which one was found. Further, if you write a library function for others to use, yet your function uses strtok(), you must document the fact so that callers of your function are not bemused by the failures of their own code that uses strtok() after calling your function. In other words, it is poisonous; if your function calls strtok(), it makes your function unreusable, in general; similarly, your code that uses strtok() cannot call other people's functions that also use it.

如果您仍然喜欢此功能的想法-有些人喜欢(但是我几乎总是避免使用它)-然后在您的系统上寻找strtok_r().它是可重入的;它需要一个额外的参数,这意味着其他功能可以使用strtok_r()(或strtok())而不会影响您的功能.

If you still like the idea of the functionality - some people do (but I almost invariably avoid it) - then look for strtok_r() on your system. It is re-entrant; it takes an extra parameter which means that other functions can use strtok_r() (or strtok()) without affecting your function.

有许多合适的替代方法.要考虑的显而易见的是strchr()strrchr()strpbrk()strspn()strcspn():这些都不会修改他们分析的字符串.所有这些都是标准C的一部分(strtok()也是如此),因此它们基本上在任何地方都可以使用.在单个字符之前查找材料建议您使用strchr().

There are a variety of alternatives that might be appropriate. The obvious ones to consider are strchr(), strrchr(), strpbrk(), strspn(), strcspn(): none of these modify the strings they analyze. All are part of Standard C (as is strtok()), so they are essentially available everywhere. Looking for the material before a single character suggests that you should use strchr().

这篇关于读取用户输入并检查字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆