C-高级取子串函数

自己写了一个高级版的取子串函数,可以完成正向取子串,反向取子串,

1、调用:

substr(取出的子串,源串,起始位置,长度)

函数返回实际取到子串的长度

其中长度可以为正数(从左边向右边取),长度为负数(从右边向左边取),长度可以超过实际能取到的子串长度,函数会智能判断,取长度范围内尽可能长的子串。

例:

int main(void){

    char dc[20];

    char *sc="deepfuture.iteye.com";

    substr(dc,sc,5,2) ;//dc为"fu"

    substr(dc,sc,5,-2) ;//dc为"pf"  

    substr(dc,sc,5,-2) ;//dc为"pf"   

    substr(dc,sc,5,-10) ;//dc为"deepf",从右边向左边取子串(-10为负数),因为10超过了能取子串的长度,所以该函数取到开始 处就停止。

    substr(dc,sc,5,100);//dc为"future.iteye.com",从左边向右边取子串(100为正数),因为100超过了能取子串的长度,所以函数取到结束处就停止。

}

2、函数源代码

int substr(char* dchr,char *schr,int begin,int len){
//作者:刘兴(deepfuturelx@gmail.com)
//取子串函数,dchr为取好后的子串,schr为源串,返回成功取出的子串数目,len为负数,则从begin向头部移动(正向),否则向尾部移动(反向),begin为起始位置(从1开始),len为子串长度

    int slen=0;

    int rc=0;    

    if (begin<=0) begin=1;//起始位置为0时,会从1开始

    slen=strlen(schr)-begin;    

    if (slen<=0||len==0){//当len为0或begin的位置已经超过源串长度时,取空串

       *dchr=NULL;

       return rc;

    }

    if (len<0){//len为负数,表示从begin处向头部移动len个字符的子串,允许出现len移过头的现象(begin=3,len=-6,则取从位置1到位置3的子串)

        len=-len;

        if(len>strlen(schr)) begin=1;

        else if((begin-len)<=0){

            len=begin;

            begin=1;

        }

        else {

             begin-=len;

             begin++;

        }

    }



     begin--;

     schr+=begin;

     int i=0;

     for(i=0;i<len&&*schr!=0;i++){

        *dchr++ = *schr++;         

     }

     *dchr=0; 

     rc=i;

  return rc;

}

 

寻找相同子串(C语言) 给你两个字符串t和p,要求从t中找到一个和p相同的连续子串,并输出该子串第一个字符的下标。但是高级语言大多已经内置实现了这些算法,比如C语言的strstr。这题目的应该是想考察子串查找算法,可以考虑使用KMP算法。 阅读详情

相关推荐

【关联子串】

已支持(Java & JS & Python & C & C++),考察:滑动窗口,尺取法

优快云 5524

C++ string字符串的增删改查

转载请标明出处: http://blog.youkuaiyun.com/u011974987/article/details/52505004 本文出自:【徐Xiho的博客】 c++ 提供的string类包含了若干实用的成员函数,大大方便了字符串的增加、删除、更改、查询等操作。插入字符串insert()函数可以在string字符串中置顶的位置插入另一个字符串,它的原型为:string& inser

stromxu 的专栏 1万+

寻找相同子串 思路+代码(华为OD-C卷-100分-Python解法)

但是高级语言大多已经内置实现了这些算法,比如Java的String的indexOf,JS的String.prototype.indexOf,Python的find函数。但是高级语言大多已经内置实现了这些算法,比如Java的String的indexOf,JS的String.prototype.indexOf,Python的find函数。但是高级语言大多已经内置实现了这些算法,比如Java的String的indexOf,JS的String.prototype.indexOf,Python的find函数。

希望我的博客,能帮上你解决学习中工作中所遇到的问题 469

c++字符串补充——取子串、比较、数组

例如: "a" < "ab", "ab" < "ac" 都是真,"ba" < "ab"是假。s[2][0]就是字符串s[2]的第0个字符'w',s[2][1]就是字符串s[2]的第1个字符'a',……string name[4]={ "zhangsan","lisi","wangwu","zhaoliu"};//定义字符串数组,包含4个字符串:name[0]、name[1]、name[2]、name[3]。例如:"aca"的子串有7个:Φ、"a"、"ac"、"aca"、"c"、"ca"、"a"。

浪子回头 3094

关联子串(C语言)

当滑窗移除一个字符c是,我们应该count[c]++,表示滑窗子串和str1的差别扩大了,此时total是否也需要+=1吗?给定两个字符串str1和str2,如果字符串str1中的字符,经过排列组合后的字符串中,只要有一个字符串是str2的子串,则认为str1是str2的关联子串。尺取法,通常是有一个子串str1,和一个父串str2,我们需要在父串str2中找到包含str1子串所有字符的目标串target,不在意字符顺序。若str1是str2的关联子串,请返回子串在str2的起始位置;

qq_34143141的博客 116

Pico-实时预览工具PreviewTool

Unity XR SDK与Preview Tool下载链接:SDK - Pico Developer Platform1、下载Preview Tool后,将PreviewTool的APK先安装在VR头显里2、在PC端打开Preview Tool.exe文件Window -> Package Manager -> Add package from disk,选择下载的pico sdk中的package.json(如下图),Open导入。Edit -> Project Settings,设置设备和安卓版本,如下

晴天下的大头娃娃 4252

C++提取子字符串

字符串

u014421313的博客 8013

iOS中.obj、.usdz、.dae和.scn格式之间的转化(思路清晰版)

作者最近在写项目的过程中遇到了一些3d模型格式问题,故写下这篇文章记录一下解决问题的过程。

yueliangmua的博客 5586

C语言:查找子串问题(strstr函数自己实现)

文章目录一、系统提供的函数:strstr二、自己实现strstr函数 一、系统提供的函数:strstr 系统提供的查找子串为:strstr。:在字符串 haystack 中查找第一次出现字符串 needle 的位置,不包含终止符 ‘\0’。 函数声明: char *strstr(const char *haystack, const char *needle) 参数: haystack:要被检索的...

Rain的博客 1万+

OPCUA二(通过OPCUA服务器访问CPU)

摘要:本文介绍了使用UaExpert软件连接西门子PLC的OPC UA配置方法,包括IP地址设置(默认端口4840)、安全认证和证书信任流程。详细说明了数据访问操作,如变量拖拽监控和属性解读(NodeId、Value、状态码等)。特别强调连接仿真Advance7时需先启动实例。最后预告下章将讲解通过KerServer访问CPU。文章涵盖配置步骤、常见问题处理及实用技巧,适合工业自动化开发者参考。

欢迎来到RaymondLeigh的知识共享基地 1339

A-Frame引擎开发:A-Frame基础入门_(11).A-Frame物理引擎集成

在上一节中,我们学习了如何在A-Frame中创建基本的3D场景和交互元素。然而,为了使虚拟现实游戏更具真实感和互动性,物理引擎的集成是必不可少的。物理引擎可以模拟现实世界中的物理行为,如重力、碰撞、摩擦等,从而增强用户的沉浸感。物理引擎在虚拟现实游戏中的重要性不言而喻。它不仅能够模拟物体的运动和相互作用,还能为游戏提供更真实的反馈和体验。例如,当玩家在虚拟世界中推动一个物体时,物理引擎可以确保物体按照预期的方式移动,而不是简单地穿墙而过或突然消失。重力是物理引擎中最基本的特性之一。在A-Frame中,我们可

chenlz2007的博客 797

C中高级取字串函数

<br />自己写了一个高级版的取子串函数,可以完成正向取子串,反向取子串,<br />1、调用:<br />substr(取出的子串,源串,起始位置,长度)<br />函数返回实际取到子串的长度<br />其中长度可以为正数(从左边向右边取),长度为负数(从右边向左边取),长度可以超过实际能取到的子串长度,函数会智能判断,取长度范围内尽可能长的子串。<br />例:<br />int main(void){<br />    char dc[20];<br />    char *sc="deepfutu

xujinquan19的专栏 633

AI游戏制作07——波次计时器,敌人按波次生成

AI游戏制作07——波次计时器,敌人按波次生成

qq_40572023的博客 47

HeadFirstC笔记_7 高级函数:发挥函数的极限

寻找真命天子…… 完成find()函数,用它过滤出ADS列表中所有运动迷,同时他们不能是Bieber的粉丝。 #include #include #include int NUM_ADS = 7;char *ADS[] = { "William: SBM GSOH likes sports, TV, dining", "Matt: SWM NS

大道至簡的博客 840

一文掌握 MongoDB 详细安装与配置(Windows / Linux / macOS 全平台)

本文详细介绍了MongoDB社区版7.0+在Windows、Linux和macOS三大操作系统上的完整安装、配置与安全加固流程。主要内容包括:各平台推荐安装方式(Windows使用MSI安装包、Linux通过官方仓库、macOS通过Homebrew)、基本配置参数说明、服务启动方法以及关键安全措施(如创建管理员用户和启用身份验证)。文章还提供了系统最低要求、下载地址、数据目录设置建议以及生产环境使用注意事项,适合开发、测试及生产环境部署参考。

数据知道的博客 6713

基于STM32设计的万能红外遥控器(学习型)

当前介绍了一种基于STM32微控制器设计的红外遥控器,支持接收解码功能和发送功能,可以将接收的码原样发送出去。 红外遥控器作为智能设备控制方式之一,在一定程度上满足了人们对于快速方便控制的需求。 当前设计的红外遥控器支持学习模式和发送模式。通过矩阵键盘上的数字键选择发送对应的控制码。 一共支持学习10个控制码,对应矩阵键盘上的数字。0~9。

6559

C语言 字符串 去除子串

strcpy(strTemp,str); while(str[i]) { if(str[i]==' ') { i++; }//跳过空格 else if(strncmp(strTemp+i,subStr,subLen)==0)//前两个为要比较的字符串,子串长度 { i=i+subLen; }//跳过要删除的字符串 else { str[j++]=...

altairtian的博客 1326

实战 | OpenCV实现扫描文本矫正应用与实现详解(附源码)

导读 本文主要介绍使用OpenCV对扫描文本矫正的应用实例及详细实现步骤。 背景介绍 在使用打印机或扫描仪扫描文档时,由于摆放位置差异难免造成扫描文档的倾斜。本文将使用OpenCV将倾斜的文档矫正水平并去除黑边。 实现步骤 本文只针对包含大部分文字的文档做倾斜矫正,思路来源是大部分文字倾斜后同一行的也在同一条直线,通过拟合直线计算文本倾斜角度,然后旋转来实现文本倾斜矫正。 详细步骤: ①加载倾斜图像 ②灰度转换+腐蚀+膨胀 ③Canny边缘检测 + 霍夫线变换检测直线 ...

Color Space的博客 3400

2016郑州大学ACM/ICPC训练赛 C 最长匹配子串

Description定义一个满足括号匹配的字符串为完美串。一个由’(‘,’)’组成的字符串,怎么才能求出 来字符串S中最长的完美串(S的子串)的长度呢?Input输入的第一行是一个数字k,代表输入的样例组数(k < 100)。 每组样例是一个字符串只由’(‘,’)’这两个字符组成的字符串s(|s| < 100000)。Output输出s中最长的匹配子串的长度。Sample Input 3

逐梦者 1905

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

C中关于字符串和字符的处理函数

介绍C语言函数库中提供的关于字符串的库函数。属于《C和指针》第9章的总结 一  字符串的概念     一串0个或多个字符组成并以NUL字节结尾的序列。    NUL字节代表着字符串的结尾,但并不是字符串的一部分,字符串的长度不包括NUL所占的一个字节。 二  字符串的存在形式     字符串可以以字符串常量或字符数组中。其中字符串常量在程序代码中指定,存储在内存代码区或文本常量区,链接之后

generalharry的专栏 1120

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

C语言常见函数/Linux系统函数

C语言函数

A_New_World的博客 840

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

shell变量的子串的删除/替换

${#string} 返回$string的长度${string:position} 在$string中,从$position位置之后开始提取子串${string:position:length} 在$string中,从$position位置之后开始提取$length长度的子串[root@localhost SHELL]# NAME="ni hao, ming tian" [root@local

github_33736971的博客 1万+

【C语言】字符串函数介绍三(strstr、strtok、streeror)

【C语言】字符串函数介绍三(strstr、strtok、streeror)

cat_with_cat的博客 632

C语言(Head First C)-8:高级函数:函数指针 qsort() 可变参数函数

8:高级函数:函数指针 qsort() 可变参数函数    基本函数很好用,但有时需要更多功能;  本章学习:      如何把函数作为参数传递,从而提高代码的智商;      学会使用比较器函数排序;      使用可变参数让代码伸缩自如;    场景:      过滤某个字符串数组中的数据;    首先用字符串函数过滤数组:  (Co

baby_hua的专栏 1528

那些进阶的C语言函数

目录 1.字符串的进阶函数 2.内存的进阶函数 1.字符串的进阶函数 我们知道了字符串有strlen,strcpy,strcmp函数其实我们看C语言库就知道还有很多函数,这里我就大概的介绍几种 1.1strnlen strtok memset ...

qq_55546526的博客 1100

perm函数c语言_理解C语言(三) 字符串处理函数

1 字符串基础字符串是一种重要的数据类型,有零个或多个字符组成的有限串行。定义子串: 串中任意个连续的字符组成的子序列,并规定空串是任意串的子串,任意串也是其自身的子串,如字符串"adereegfb"中它本身、空串、诸如"ader"连续的字符串都是它的子串。子序列则不要求字符连续,但顺序要与主串保持一致,若有"abcd"与"ad"则两者的最长公共子序列为"ad"。在动态规划中计算最长公共子序列和最...

weixin_39973196的博客 664
上一篇: linux-c-curses(1)-颜色+中文
下一篇: linux-Linux终端图形库curses-C-窗口与子窗口
deepfuture
博客等级 码龄17年 210粉丝 1287原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值