c#寻找字符串子字符串
时间: 2023-11-27 15:59:37 浏览: 43
在C#中,可以使用字符串的IndexOf方法来查找子字符串。例如,以下代码可以查找字符串“hello world”中是否包含子字符串“world”:
```
string str = "hello world";
int index = str.IndexOf("world");
if (index != -1)
{
Console.WriteLine("Substring found at index " + index);
}
else
{
Console.WriteLine("Substring not found");
}
```
注意,IndexOf方法返回子字符串的第一个字符的索引。如果子字符串不存在,则返回-1。
相关问题
c语言判断字符串子字符串
可以使用库函数strstr(),例如:
```c
char *str1 = "hello world";
char *str2 = "world";
char *ptr = strstr(str1, str2);
if (ptr) {
printf("找到子字符串:%s\n", ptr);
} else {
printf("未找到子字符串\n");
}
```
这段代码中,str1为原始字符串,str2为要查找的子字符串,strstr()函数返回子字符串在原始字符串中第一次出现的位置,如果找到了则返回指向该位置的指针,否则返回NULL。可以通过判断返回值是否为NULL来确定是否找到子字符串。
c语言查找字符串子串
可以使用C语言中的strstr函数来查找字符串子串。该函数的原型为:
```c
char *strstr(const char *str1, const char *str2);
```
其中,str1为要查找的字符串,str2为要查找的子串。函数返回值为指向第一次出现子串的指针,如果没有找到则返回NULL。
示例代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "hello world";
char str2[] = "world";
char *ptr = strstr(str1, str2);
if (ptr != NULL) {
printf("子串在字符串中的位置:%d\n", ptr - str1);
} else {
printf("未找到子串\n");
}
return 0;
}
```
输出结果为:
```
子串在字符串中的位置:6
```
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)