C语言在字符串A中查找字符串B
时间: 2023-09-03 11:15:44 浏览: 107
可以使用strstr函数来在字符串A中查找字符串B,该函数定义在string.h头文件中。示例代码如下:
```c
#include <stdio.h>
#include <string.h>
int main() {
char strA[100] = "Hello world";
char strB[10] = "world";
char* p = strstr(strA, strB);
if (p != NULL) {
int index = p - strA; // 计算字符串B在字符串A中的位置
printf("字符串B在字符串A中的位置是:%d\n", index);
} else {
printf("字符串A中没有找到字符串B\n");
}
return 0;
}
```
输出结果为:
```
字符串B在字符串A中的位置是:6
```
上述代码中,首先定义了两个字符数组strA和strB,其中strA表示要查找的字符串,strB表示要查找的子字符串。然后使用strstr函数来查找字符串B在字符串A中的位置,如果找到了,则返回字符串B在字符串A中的指针,否则返回NULL。最后计算出字符串B在字符串A中的位置,并输出结果。
相关问题
c语言输入两行字符串 a 和 b,查找 a 中子串 b 的位置
你好!对于你的问题,我可以给出以下的C语言代码实现:
```
#include <stdio.h>
#include <string.h>
int main()
{
char a[100], b[100];
int i, j, flag;
printf("请输入字符串a:");
gets(a);
printf("请输入字符串b:");
gets(b);
for(i=0; i<=strlen(a)-strlen(b); i++)
{
flag = 1;
for(j=0; j<strlen(b); j++)
{
if(a[i+j] != b[j])
{
flag = 0;
break;
}
}
if(flag == 1)
{
printf("子串b在字符串a中的位置是:%d\n", i+1);
return 0;
}
}
printf("字符串a中不存在子串b!\n");
return 0;
}
```
当然,如果你对这段代码有任何疑问,也可以继续向我提问哦!
C语言查找两个字符串中的最大公共子串
可以使用动态规划算法来查找两个字符串中的最大公共子串。具体步骤如下:
1. 定义一个二维数组dp,其中dp[i][j]表示以第一个字符串的第i个字符和第二个字符串的第j个字符结尾的最长公共子串的长度。
2. 初始化dp数组,将第一行和第一列都赋值为0。
3. 遍历两个字符串,如果第一个字符串的第i个字符和第二个字符串的第j个字符相等,则dp[i][j] = dp[i-1][j-1] + 1;否则dp[i][j] = 0。
4. 在遍历的过程中,记录下最长的公共子串的长度和结束位置。
5. 根据结束位置和最长公共子串的长度,可以得到最长公共子串。
以下是示例代码:
```c
#include <stdio.h>
#include <string.h>
void findLCS(char *str1, char *str2)
{
int len1 = strlen(str1);
int len2 = strlen(str2);
int dp[len1+1][len2+1];
int maxLen = 0;
int endPos = 0;
memset(dp, 0, sizeof(dp));
for (int i = 1; i <= len1; i++) {
for (int j = 1; j <= len2; j++) {
if (str1[i-1] == str2[j-1]) {
dp[i][j] = dp[i-1][j-1] + 1;
if (dp[i][j] > maxLen) {
maxLen = dp[i][j];
endPos = i;
}
} else {
dp[i][j] = 0;
}
}
}
if (maxLen == 0) {
printf("没有找到公共子串\n");
} else {
printf("最长公共子串为:");
for (int i = endPos - maxLen; i < endPos; i++) {
printf("%c", str1[i]);
}
printf("\n");
}
}
int main()
{
char str1[] = "abcdefg";
char str2[] = "bcdehij";
findLCS(str1, str2);
return 0;
}
```
输出结果为:
```
最长公共子串为:bcde
```