目录
主串中查找子串
7-29 删除字符串中的子串
7-30 字符串的冒泡排序
主串中查找子串
查找子串在主穿的中出现的位置
函数strstr(s1,s2),返回的是s2在s1中出现的位置指针
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
int main(){
char s1[100];
char s2[100];
gets(s1);
gets(s2);
int n=strlen(s1);
int m=strlen(s2);
int j=0,i=0;
while (i < n){
j = 0;
while (s1[i+j] == s2[j] && j < m) {
j++;
}
if (j == m){
printf("找到了字串在:%d的地方",i);
return 0;// 找到了相同的子串
}else{
i++;
}
}
printf("找不到");
return 0;
}
7-29 删除字符串中的子串
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
int main(){
char s1[100];
char s2[100];
gets(s1);
gets(s2);
int n=strlen(s1);
int m=strlen(s2);
int j=0,i=0;
while (i < n) {
int j = 0;
while (s1[i+j] == s2[j] && j < m) {
j++;
}
if (j == m) { // 找到了相同的子串
for (int k = i +m; k < n; k++) {
s1[k-m] = s1[k];
}
n -= m;
i = 0; // 重新检查是否还存在子串
} else {
i++;
}
}
s1[n] = '\0'; // 在删除子串后,需要手动添加字符串结束符
printf("%s", s1);
return 0;
}
7-30 字符串的冒泡排序
#include<stdio.h>
#include<string.h>
main(){
int n,k;
scanf("%d %d\n",&n,&k);
char data[n][11],tmp[11];
int i,j,a;
for(i=0;i<n;i++){
gets(data[i]);
}//输入字符串
for(i=1;i<=k;i++){//排K遍字符串
for(j=0;j<n-i;j++){//较大的字符串在最后,已排好序
a=strcmp(data[j],data[j+1]);//比较
if(a>0){//交换
strcpy(tmp,data[j]);
strcpy(data[j],data[j+1]);
strcpy(data[j+1],tmp);
}
}
}
for(i=0;i<n;i++){
printf("%s\n",data[i]);
}
}