首页 > 其他分享 >【C】关于字符串与字符串函数de一些小练习

【C】关于字符串与字符串函数de一些小练习

时间:2024-08-31 21:21:48浏览次数:12  
标签:练习 return int de char str 字符串 const

关于字符串与字符串函数de小练习


1.字符串中的最大数

你需要找出十个数中最大的哪一个,但不幸的是因为一些故障,一些小写字母随机的插入了这是个数字。请忽视这十个字符串中无意义的小写字母,输出这十个数字中最大的那一个,以及它来自于哪一个字符串。

输入:

"a3a2dsa3f4fsa5dgf";
"b2345fsa5dgf";
"2344h25ihiooy2";
"a3a234g5dgf";
"a3a2ds324fdgrhdgf";
"a3fghdfgsddgf";
"sad87f89q374";
"drghe478502";
"2re9fu02987r";
"32wtewr939rgu";

输出:

max number is 8789374
comes from sad87f89q374

题解:使用strpbrk()函数,可以查找一个字符串当中符合一个特定字符集合的字符,并返回一个指向它的指针。借由这种方式找出字符串中的数字,合成一个整数,并找出最大数即可。

#include <stdio.h>
#include <string.h>

int get(char const *string);
int find(char **,int *);

int main() {
    char *p[10];
    p[0] = "a3a2dsa3f4fsa5dgf";
    p[1] = "b2345fsa5dgf";
    p[2] = "2344h25ihiooy2";
    p[3] = "a3a234g5dgf";
    p[4] = "a3a2ds324fdgrhdgf";
    p[5] = "a3fghdfgsddgf";
    p[6] = "sad87f89q374";
    p[7] = "drghe478502";
    p[8] = "2re9fu02987r";
    p[9] = "32wtewr939rgu";
    int maxlabel = 0;
    int *plabel = &maxlabel;
    int max = find(p,plabel);

    printf("max number is %d\ncomes from %s\n",max,p[maxlabel]);

    return 0;
}

int find(char **p,int *plabel){
    int num[10],max=0;
    *plabel=0;
    for(int i = 0;i<10;i++){
        num[i] = get(p[i]);
        *plabel = (num[i]>max) ? i : *plabel ;
        max = (num[i]>max) ? num[i] : max ;
    }
    return max;
}

int get(char const *string){//输入字符串,输出转换后的数字

    char *p = strpbrk(string,"0123456789");//指向了第一个数字
    int num = 0 ;
    while(1){
        num *= 10;
        num += ((int)*p-(int)'0');
        string = p + 1;
        if(*string == '\0'){break;}
        p = strpbrk(string,"0123456789");
        if(p == NULL){break;}
    }
    return num;
}

2.摘抄好句

阅读一段仅由空格逗号,句号,大小写字母组成的英语文本,并从中找出最长的一句话,将其打印出来。

输入:

"This mentality counts in almost every stage of our life.First, when a student keeps learning new skills, he or she always asks for more and desires to explore the unknown world. Therefore, there is an excellent chance that he or she stands out in peer groups. Second, in the workplace,office workers with such attitude generally finish his or her tasks in a higher quality, and they are more likely to climb up the ladder more quickly than their colleagues who content themselves with the skills they already have.Besides, in our daily life, people who keep learning new skills are more positive, and everyone around them must be fond of making friends with them."

输出:

Longest sentence is
Second, in the workplace,office workers with such attitude generally finish his or her tasks in a higher quality, and they are more likely to climb up the ladder more quickly than their colleagues who content themselves with the skills they already have.

题解:使用strtok()函数可以分割字符串,这里只需要分割句号结尾的就是一个句子了。strlen()函数可以获取字符串长度,借此就可以找出“最长的句子”了。

#include <stdio.h>
#include <string.h>
char *longsentence(char * string);

int main(void){
char string[] = "This mentality counts in almost every stage of our life.First,"
" when a student keeps learning new skills, he or she always asks for more and de"
"sires to explore the unknown world. Therefore, there is an excellent chance that he "
"or she stands out in peer groups. Second, in the workplace,office workers with such a"
"ttitude generally finish his or her tasks in a higher quality, and they are more like"
"ly to climb up the ladder more quickly than their colleagues who content themselves "
"with the skills they already have.Besides, in our daily life, people who keep lear"
"ning new skills are more positive, and everyone around them must be fond of makin"
"g friends with them.";
    char *p = longsentence(string);
    printf("Longest sentence is\n%s.",p);
    return 0;
}

char *longsentence(char * string){
    char *p = strtok(string,".");
    int maxlength = strlen(p);
    char *sentence = p;
    while(1){
        p = strtok(NULL,".");
        if(p==NULL)
            break;
        if(strlen(p)>maxlength){
            maxlength = strlen(p);
            sentence = p;
        }
    }
    return sentence;
}


3.回文字符串

判断一个字符串是否是回文串。回文串是指从左往右以及从右往左阅读都完全相同的字符串。

输入:

"sdasfsads"

输出:

yes

题解:只需要验证两边内容一致即可

#include <stdio.h>
#include <string.h>
int test(char const *str);

int main(void){
    char string[] ="sdasfsads";
    int a = test(string);
    if(a==1){printf("yes");}else{printf("no");}
    return 0;
}

int test(char const *str){
    int length = strlen(str);
    if(length < 2)
        return 1;
    int p1 = 0;
    int p2 = length-1;
    length/=2;
    for(int i = 0;i<length;i++){
        if(str[p1]==str[p2]){
            p1+=1;
            p2-=1;
        }else{return 0;}
    }
    return 1;
}

4.粘贴一个回文字符串 ①

通过将其中两个字符串进行粘贴在一起,可以获得一个新字符串。
判断一下,能否通过这种方式粘贴两个字符串,创造出一个回文字符串呢?

题解:直接连接,用strcat()函数,再判断一下是不是回文串。

int test(char const *str){
    int length = strlen(str);
    if(length < 2)
        return 1;
    int p1 = 0;
    int p2 = length-1;
    length/=2;
    for(int i = 0;i<length;i++){
        if(str[p1]==str[p2]){
            p1+=1;
            p2-=1;
        }else{return 0;}
    }
    return 1;
}

int paste(char const *s1,char const *s2){
    char *str = malloc(sizeof(char)*20);
    strcpy(str,s1);
    int a = test(strcat(str,s2));
	free(str);
    return a;
}

5.粘贴一个回文字符串 ②

这一次和上一道题一样,不过我们一下子有了许许多多的字符串,现在需要考虑的是:
能否在这一大堆字符串当中挑出来其中两个,粘贴成一个回文串。
你需要探究是否可行的同时,还要将粘贴过后的字符串打印出来。

输入:

"abc";
"dcba";
"efg";
"ert";
"rty";

输出:

true
abcdcba

题解:有了前面两道题的铺垫,这样就比较容易解决这种问题了。最简单的想法当然是用两层for循环来尝试所有这些字符串,将其正反拼接一次,看看能否得到一个回文串。
再次用到前两问的函数即可。下面是完整代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int test(char const *str);
int stick(char const *,char const *);
char *find(char **p,int psize);

int main(void){
    char *p[5];
    p[0] = "abc";
    p[1] = "dcba";
    p[2] = "efg";
    p[3] = "ert";
    p[4] = "rty";
    char *s = find(p,5);
    if(s == NULL){printf("false");}
	else{printf("true\n%s",s);}
    return 0;
}

char *find(char **p,int psize){
    if(psize == 0){return NULL;}
    if(psize == 1){return (test(p[0]) == 1)?p[0]:NULL;}
    char *store = malloc(sizeof(char)*10);
    for(int i = 0;i < psize - 1;i++){
        for(int j = i+1;j < psize;j++){
            if(stick(p[i],p[j]) == 1){
				strcpy(store,p[i]);
				return strcat(store,p[j]);
			}
            if(stick(p[j],p[i]) == 1){
				strcpy(store,p[j]);
				return strcat(store,p[i]);
			}
        }
    }
    return NULL;
}

int test(char const *str){
    int length = strlen(str);
    if(length < 2)
        return 1;
    int p1 = 0;
    int p2 = length-1;
    length/=2;
    for(int i = 0;i<length;i++){
        if(str[p1]==str[p2]){
            p1+=1;
            p2-=1;
        }else{return 0;}
    }
    return 1;
}

int stick(char const *s1,char const *s2){
    char *str = malloc(sizeof(char)*20);
    strcpy(str,s1);

    int a = test(strcat(str,s2));

    free(str);
    return a;
}


6.元音字母转换

给你一个字符串,现要求你对其进行处理,使得处理后的字符串满足如下要求:
字符串里面的元音字母全部为大写;
其余字母全部为小写。

输入:

4
XYz
application
qwcvb
aeioOa

输出:

true
abcdcba

题解:只需要运用字符串查找函数strpbrk在字符串中查找即可。可以先将所有字母变为小写,再将其中的aeiou字母变为大写。变换大写小写需要用到touppertolower函数。

#include <string.h>
#include <ctype.h>
#include <stdio.h>

int main(void){
    int num=0;
    scanf("%d",&num);
    char* input[num];
    for(int i=0;i<num;i++){
        input[i]=malloc(sizeof(char)*50);
        scanf("%s",input[i]);
    }
    char *p=input[0];
    int ab=0;
    char const *group="aeiou";
    char const *group_upper="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    for(int i=0;i<num;i++){
        p=input[i];
        while(strpbrk(input[i],group_upper)!=NULL){
		*strpbrk(input[i],group_upper)=tolower(*strpbrk(input[i],group_upper));
        }
        while(strpbrk(input[i],group)!=NULL){

            *strpbrk(input[i],group)=toupper(*strpbrk(input[i],group));
        }
    }

    for(int i=0;i<num;i++){
        printf("%s\n",input[i]);
    }
    return 0;
}


本系列博客为我本人原创的学习笔记,尽量勤更新,如有错误欢迎各位大佬指出,Thanks♪(・ω・)ノ

标签:练习,return,int,de,char,str,字符串,const
From: https://blog.csdn.net/u011046264/article/details/141758162

相关文章

  • equals ,hashcode ,== ,三者之间的关系与区别
    为什么要重写equals和hashcode        在Java中,重写equals方法和hashCode方法是为了确保对象在逻辑上相等时,它们在集合(如HashMap、HashSet)中的行为也是一致的。以下是详细解释:为什么要重写 equals 方法默认行为:默认情况下,Object类的equals方法比较的是两个对......
  • 大模型agent开发之loader
    loader加载器的主要作用是加载各种格式的知识库给大模型进行学习,从而提升大模型在专业领域的能力,也是创建大模型agent开发的第一步。 TextLoader在langchain中TaxtLoader加载器可以加载.md,.test等格式的文档,需要注意的是中文文档需要指明解析字符集格式。#使用loader加......
  • Altium Design设置原理图图纸大小
    点击原理图右下角Panels选项,选择Properties打开在Properties界面可以对图纸单位,图纸大小,方向,边缘尺寸等进行调整图纸模版包括:模型图纸:  A0_portrait~A4_portrait公制图纸:A0~A4英制图纸:A~ECAD标准图纸: A~EOrCAD标准图纸:Orcad_a~ Orcad_e其他格式......
  • 【保姆级VSCode 插件开发之创建第一个插件项目】
    保姆级VSCode插件开发第一章VSCode插件开发入门之创建第一个插件项目文章目录保姆级VSCode插件开发前言一、创建HelloWorld插件项目1.创建项目2.VSCode打开项目2.1项目目录结构:总结前言本篇文章主要介绍如何创建你的第一个VSCode插件项目"HelloWorld",来......
  • 数据结构:(LeetCode965)单值二叉树
     一:定义如果二叉树每个节点都具有相同的值,那么该二叉树就是单值二叉树。只有给定的树是单值二叉树时,才返回 true;否则返回false。示例1:输入:[1,1,1,1,1,null,1]输出:true示例2:输入:[2,2,2,5,2]输出:false 提示:给定树的节点数范围是 [1,100]。每个节点的值都是......
  • 数据结构:(LeetCode 965)相同的树
    给你两棵二叉树的根节点 p 和 q ,编写一个函数来检验这两棵树是否相同。如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。示例1:输入:p=[1,2,3],q=[1,2,3]输出:true示例2:输入:p=[1,2],q=[1,null,2]输出:false示例3:输入:p=[1,2,1]......
  • Docker Push Error "denied: requested access to the resource is denied": 终极解决
    预览版:终极解决方案——把库删了,再重新建一个名字一样的,然后push一般dockerlogin登录之后,sudodockerpushusername/dockername:latest就能成功push了。然后我还是有报错:xxxxxxxxxxxx:Preparingxxxxxxxxxxxx:Preparingxxxxxxxxxxxx:Preparingxxxxxxxxxxxx:Preparing......
  • YOLO系列和RT-DETR转onnx和tensorrt,测FPS
    RT-DETR(RT-DETR:DETRsBeatYOLOsonReal-timeObjectDetection)和YOLOv8等在最后加nmsRT-DETR转onnx和tensorrt和RT-DETR转onnx和tensorrt步骤流程:1.nvidia驱动,cuda,cudnn三者的版本是相互对应的,必须要确保版本匹配(https://blog.csdn.net/qq_41246375/article/det......
  • Hausdorff Distance 和 Euclidean Distance Mean欧氏距离
    importtorchimporttorch.nnasnnclassHausdorffDistanceLoss(nn.Module):def__init__(self):super(HausdorffDistanceLoss,self).__init__()defforward(self,pred,target):#扩展为(B,N,1,D)和(B,1,M,D)pred=pred......
  • python 基础习题7--for循环练习
    1.编写一个程序,判断输入的一个数字是否为偶数。示例输入:3返回:yes示例输入:4返回:no2.编写一个程序,找出列表中的大于50的数,并输出该数及其在列表中的索引位置。该列表可以自己写,例如:[23,78,1,56,35,60,90]输出:7815636059063.编写一个程序,统计一个字符串中字母"a"出现的次数......