/**
* @Name:字符串的常见操作
* @Description:串的连接、比较、求子串、模式匹配、分割等。
* @Author:Freedoman
* @Date: 2014-8-13
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <conio.h>
#define MAX 100
/*----------计算字符串的长度---------*/
int getLength(char * pstr)
{
int i = 0;
while(pstr[i] != '\n')
{
i++;
}
return i;
}
/*--------连接两个字符串-------*/
char * concatString(char * pstr1, char * pstr2)
{
char str[1024];
char * pstr = str;
int i = 0, j = 0;
// pstr1
while(pstr1[j] != '\n')
{
pstr[i++] = pstr1[j++];
}
// pstr2
j = 0;
while(pstr2[j] != '\n')
{
pstr[i++] = pstr2[j++];
}
pstr[i] = '\n';
return pstr;
}
/*----------比较两个串的大小----------*/
int compareString(char * pstr1, char * pstr2)
{
int i = 0;
while(pstr1[i] != '\n' && pstr2[i] != '\n')
{
if(pstr1[i] == pstr2[i])
{
i++;
continue;
}
}
return pstr1[i] - pstr2[i];
}
/*------------截取子串---------*/
char * subString(char * pstr,int index ,int length)
{
char subStr [1024];
char * pSubStr = subStr;
int i = 0, j = 0;
for(i = 0; i < length; i++)
{
pSubStr[i] = pstr[index+i];
}
pSubStr[i] = '\n';
return pSubStr;
}
/*------------字符头尾虑空------------*/
char * trimString(char * pstr)
{
char * subStr = (char *)malloc(sizeof(char)*strlen(pstr));
int i = 0, j = strlen(pstr)-1;
int k,m;
while(pstr[i] == ' ')
{
i++;
}
while(pstr[j] == ' ')
{
j--;
}
for(k = i,m=0; k <= j; k++,m++)
{
subStr[m] = pstr[k];
}
subStr[m] = '\0';
return subStr;
}
/*----------判断一个字符串包含另一个字符串----------*/
int containsString(char * p, char * t)
{
int i = 0 , j = 0;
while(p[i] != '\0' && t[j] != '\0')
{
if(p[i] == t[j])
{
i++;
j++;
}
else
{
i = i - j + 1;
j = 0;
}
}
// 判断是匹配成功还是到达字符串的尾
if(j == strlen(t))
{
return 1;
}
return 0;
}
/*--------串的朴素模式匹配(暴力搜索)--------*/
int bruteForce(char * p, char * t)
{
int i = 0, j = 0;
while(p[i] != '\n' && t[j] != '\n')
{
// 只要相等就一直比较只到模式结束
if(p[i] == t[j])
{
i++;
j++;
}
else
{
//回溯
i = i-j+1;
j = 0;
}
}
// 模式结束后有两种结果
if(j == getLength(t))
{
return i-j;
}
else
{
return -1;
}
}
/*---------用一个字符替换另一个字符----------*/
void replace(char * p , char oldChar, char newChar)
{
while(*p != '\0')
{
if(*p == oldChar)
{
*p = newChar;
}
p++;
}
}
/*------使用一个字符切割字符串-------*/
char ** split(char * p, char regex)
{
int curIndex = 0,index = 0;
int startIndex = curIndex;
char * result[strlen(p)];
while(p[curIndex] != '\0')
{
if( p[curIndex] == regex )
{
// 申请一个字符串指针存储分割结果
char * string = (char *)malloc(1024);
int i , j = 0;
for(i = startIndex; i < curIndex; i++)
{
string[j++] = p[i];
}
string[j] = '\0';
result[index++] = string;
startIndex = curIndex+1;
}
curIndex ++;
}
// 申请一个字符串指针存储分割结果
char * string = (char *)malloc(1024);
int i , j = 0;
for(i = startIndex; i < curIndex; i++)
{
string[j++] = p[i];
}
string[j] = '\0';
result[index++] = string;
startIndex = curIndex+1;
return result;
}
/**
* @Description:
* @Arguments:
* @Returns:
*/
int main()
{
return 0;
}
字符串的基本操作
最新推荐文章于 2023-02-03 18:03:08 发布