c - 在字符串 ( C ) 中最后一次出现 :: 之后打印所有内容的应用程序
问题描述
我正在尝试编写一个在最后一次出现 2 个冒号“::”之后打印所有内容的应用程序,所以如果它是 3 个“:::”,它就不算数。如果字符串是“He::ll::o”,它应该打印出“o”,如果它是“12312::233”,它应该打印出“233”,我必须使用一个我今天刚开始学习char* extract(char* input);
的指针函数我有点不知所措。我也不允许导入库。这就是我到目前为止所拥有的。任何帮助表示赞赏。void extract2(char* input, char** output)
C
int isCH(char c) {
return (c != ':' && c != '\0');
}
char *extract(char *input){
int state = 1;
char *doubleColon;
while(1){
switch(state){
case 1:
if(isCH(*input))
state = 1;
if(*input == '\0')
state = 2;
if(*input == ':') // first colon
state = 3;
break;
case 2:
return doubleColon;
break;
case 3:
if(isCH(*input))
state = 1;
if(*input == '\0')
state = 2;
if(*input == ':'){ // second colon
state = 4;
doubleColon = input;
}
break;
case 4:
if(isCH(*input))
state = 1;
if(*input == '\0')
state = 2;
if(*input == ':')
state = 1;
break;
}
input++;
}
}
int main() {
printf("End of String: %c", *extract("Ha::ll::o"));
}
解决方案
更通用的功能。在最后一次出现任何分隔符后,它将返回指向剩余字符的指针。
char *extract(char *input, const char *del)
{
char *last = NULL, *current = NULL;
size_t delLength = strlen(del);
if(input && del && *del)
{
do
{
if(current)
{
last = current + delLength;
input = last;
}
}while((current = strstr(input, del)));
}
return last;
}
int main() {
char *res;
printf("End of String: %s\n", (res = extract("Ha::ll::o", "::")) ? res : "Not found");
printf("End of String: %s\n", (res = extract("Ha::ll::o", ":ll:")) ? res : "Not found");
printf("End of String: %s\n", (res = extract("", "::")) ? res : "Not found");
printf("End of String: %s\n", (res = extract(NULL, "::")) ? res : "Not found");
}
推荐阅读
- python-3.x - 在 Pandas 中重新排列列然后连接
- database - 我需要规范化我的 SQLite3 数据库吗?
- hadoop - Presto 与 hive 的集成不起作用
- javascript - 即使遵循 react-navigation 文档,react-navigation 也无法在屏幕之间导航
- c - 参数没有从输入函数中传递出去
- sql - 如何使用 SQL Server 检索月份数据?
- python - Python 日志查询
- oracle - oracle中有“立即执行”时如何实现refcursor?
- reactjs - 如何访问数组对象中的元素 [API]
- reactjs - 当InfiniteScroll在reactjs中向下滚动时如何保持其他组件保持在顶部位置