C代码和python代码:字符替换

一、总结

好久没学习代码了,而且只是简单学习了Python后来改这个后真的是一个头两个大,感觉真的有挺多和C不一样的
C有指针,Python没有
C没有直接的String类型,Python有
然后就各种熟悉Python字符串的用法

总结了一些改程序中遇到的问题
1、因为C没有直接的String类型,Python有,所以直接使用String类型的变量就好,不用使用列表,函数的参数直接使用String就行,因为看到*就陷入误区的我…
2、可以直接使用 len( str) 来得到 str 的长度,就可以将其用于循环
3、TypeError: ‘str’ object does not support item assignment
python中的String是不可变类型的,不能直接使用 s[ i ] = s2[ i ] 这种写法,而要 s = s[:i] + s2[i] + s[i+1:]
4、最后记得返回值,这是个低级错误

二、Python代码

运行环境:VS2017
以下是代码:

#include <stdio.h>
#include <stdlib.h>
#define MAX 50
/* 函数rep实现对s中出现的s1中的字符替换为s2中相应的字符 */
void rep(char *s,char *s1,char *s2)
{
	char *p;

	for( ; *s; s++)/*顺序访问字符串s中的每个字符*/
	{
		for( p = s1; *p && *p != *s; p++);/*检查当前字符是否在字符串s1中出现*/
		if( *p)
			*s = *( p - s1 + s2);/*当前字符在字符串s1中出现,用字符串s2中的对应字符代替s中的字符*/
	}
}
int main( )/*示意程序*/
{
	char s[MAX];/*="ABCABC";*/
	char s1[MAX],s2[MAX];
	system("cls");

	puts("Please input the string for s:");
	scanf_s("%s", s, MAX);
	puts("Please input the string for s1:");
	scanf_s("%s", s1, MAX);
	puts("Please input the string for s2:");
	scanf_s("%s", s2, MAX);

	rep( s, s1, s2);
	puts("The string of s after displace is:");
	printf("%s\n",s);
	
	system("pause");
	return 0;
}

三、Python代码

运行环境:Pycharm,python3.74
以下是代码:


def main( ): #示意程序
	print("Please input the string for s:")
	s = input()
	print("Please input the string for s1:")
	s1 = input()
	print("Please input the string for s2:")
	s2 = input()

	s = rep( s, s1, s2)
	print("The string of s after displace is:", end = '')
	print( s)

# 函数rep实现对s中出现的s1中的字符替换为s2中相应的字符
def rep( s, s1, s2):

	for i in range(0, len(s)):#顺序访问字符串s中的每个字符
		key = 0
		for j in range(0, len(s1)):	#检查当前字符是否在字符串s1中出现*/
			if s1[j] == s[i]:
				key = 1
				break
		if key == 1:	#当前字符在字符串s1中出现,用字符串s2中的对应字符代替s中的字符
			s = s[:i] + s2[i] + s[i+1:]
	return s

main()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值