如何创建一个在C中返回子字符串的函数? [英] How do I make a function that returns a substring in C?

查看:127
本文介绍了如何创建一个在C中返回子字符串的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在过去的一天里,我一直试图修复此代码无济于事。我正在尝试创建一个简单的函数,它接受两个字符串并找到两者之间的子串(Needle和Haystack)。有人可以帮帮我吗?



我尝试过:



For the past day I have been trying to fix this code to no avail. I am trying to make a simple function that takes in two strings and finds the substring between the two (Needle and Haystack). Can someone help me??

What I have tried:

char* stringString(char *needle, char *haystack) {

	int i, j;
	char *sub;
	for (i = 0; i < strlen(haystack); i++) {
		sub = &haystack[i];
		for (j = 0; j < strlen(needle); j++) {
			
			if (haystack[i + j] != needle[j]) {
				continue;
			}
			
			if (needle[j] == 0) {
				return sub;
			}
			else
				i = i - j;
			if (haystack[i] == NULL)
				i--;
		
		}
		return sub;
	}
	return -1;
	}

推荐答案

你想重新发明这个轮子吗?



strstr - C ++参考 [ ^ ]
Are you trying to reinvent this wheel?

strstr - C++ Reference[^]


这篇关于如何创建一个在C中返回子字符串的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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