- 定义函数 返回某个字符在字符串中第一次出现的位置
#include <stdio.h>
int num(char *, char );
int main(){
char a[10];
char b;
printf("请输入字符串和字符");
scanf("%s %c", a, &b);
printf("首次出现位置为:%d", num(a, b));
return 0;
}
int num(char *arr, char c)
{
int n = 0;
while ( *arr != '\0')
{
if (*arr == c)
{
break;
}
n++;
*arr++;
}
return n;
}
- 定义函数 返回某个字符在字符串中最后一次出现的位置
#include <stdio.h>
#include <string.h>
int lastIndex(char *, char);
int main()
{
char a[10];
char b;
printf("请输入字符串和字符");
scanf("%s %c", a, &b);
printf("最后出现位置为:%d", lastIndex(a, b));
return 0;
}
int lastIndex(char *arr, char c)
{
int n = 0;
int s = strlen(arr);
for (int i = 0; i < s; i++)
{
if (arr[i] == c)
{
n = i;
}
}
return n;
}
- 定义函数 实现字符串中小写字母转大写字母;
#include <stdio.h>
void *upperCase(char *);
int main()
{
char aa[10];
printf("请输入字符串");
scanf("%s", aa);
upperCase(aa);
printf("%s", aa);
return 0;
}
void *upperCase(char *s)
{
while (*s != '\0')
{
if (*s >= 'a' && *s <= 'z')
{
*s -= 32;
}
*s++;
}
}
- 定义函数 实现字符串中大写字母转小写字母;
#include <stdio.h>
void *lowerCase(char *);
int main()
{
char aa[10];
printf("请输入字符串");
scanf("%s", aa);
lowerCase(aa);
printf("%s", aa);
return 0;
return 0;
}
void *lowerCase(char *s)
{
while (*s != '\0')
{
if (*s >= 'A' && *s <= 'Z')
{
*s += 32;
}
*s++;
}
}
- 定义函数,实现交换两个变量的值; 函数原型
#include <stdio.h>
void exchange(int *, int *);
int main()
{
int n1, n2;
printf("请输入两个整数: ");
scanf("%d %d", &n1, &n2);
exchange(&n1, &n2);
printf("%d %d", n1, n2);
return 0;
}
void exchange(int *a, int *b)
{
int c;
c = *a;
*a = *b;
*b = c;
}