展会信息港展会大全

用shell脚本和c语言将大写字母转成小写的代码
来源:互联网   发布日期:2016-01-19 13:03:11   浏览:1997次  

导读:最近在学shell编程,在网上看到tr 39;[:upper:] 39; 39;[:lower:] 39; 可以把字符串中大写字母转换成小写字母,我就在这个的基础上写了一个脚本来自己学习学习复制代码 代码如下: ! bin bash name: u ...

最近在学shell编程,在网上看到tr '[:upper:]' '[:lower:]' 可以把字符串中大写字母转换成小写字母,我就在这个的基础上写了一个脚本来自己学习学习

复制代码 代码如下:

#!/bin/bash

#name: upper_to_lower.sh

#the function is trun uper to lower

#like ABCd to abcd

haveuppernumber()

{

#test if the string have upper number

str="$(echo $1 | tr '[:upper:]' '[:lower:]')"

if [ "$str" != $1 ] ; then #get some problem

echo "[#have upper number,and i well trun them to lower:#]"

return 1 #have upper number

else

return 0 #no upper number

fi

}

if [ $# -ne 1 ] ; then

echo "Usage: $0 <string>" >&2

exit 1

fi

if ! haveuppernumber $1 ; then #when if is 0 it run?

#if [ 0 ] ; then #in shell true return 0 ,false return 1

echo $1 | tr '[:upper:]' '[:lower:]' #it can turn the UPPER number to lower

#echo $1 | tr '[:lower:]' '[:upper:]' #it can turn the lower number to UPPER

else

echo "[#no upper number:#]"

echo $1

fi

exit 0

功能说明:当输入 ./upper_to_lower.sh AaBbCcdd 时会先判断输入格式是否正确,然后判断字符串中是否有大写字母如果有显示"[#have upper number,and i well trun them to lower:#]"和转换成小写字母后的字符串;如果没有大写字母显示"[#no upper number:#]"和小写字符串。

然后又试着用c语言实现相同的功能,如下:

复制代码 代码如下:

#include<stdio.h>

#include<stdlib.h>

int haveuppernumber(char *p)

{

char*q=p;

for(;*q!='';q++)

{

if(*q>='A'&&*q<='Z')

{

printf("[#have upper number and i will turn them to lower #]n");

return 1;

}

}

printf("[#no upper number#]n");

return 0;

}

void turntolower(char *p)

{

for(;*p != '';p++)

{

if(*p>='A' && *p<='Z')

{

*p+=' ';

}

}

}

int main(int argc , char *argv[])

{

char *p;

p=argv[1];

if(argc != 2)

{

printf("Usage : %s <string>n",argv[0]);

exit(-1);

}

if(haveuppernumber(p))

{

turntolower(p);

printf("%sn",argv[1]);

}

else

{

printf("%sn",argv[1]);

}

return 0;

}

赞助本站

人工智能实验室

相关热词: shell脚本 c语言

AiLab云推荐
展开

热门栏目HotCates

Copyright © 2010-2024 AiLab Team. 人工智能实验室 版权所有    关于我们 | 联系我们 | 广告服务 | 公司动态 | 免责声明 | 隐私条款 | 工作机会 | 展会港