您的位置:首页 > 编程语言 > Python开发

python和JAVA之for循环的区别

2016-06-01 15:36 555 查看
写C和JAVA的for循环多了,把python的For循环语句都快忘了。

一个判断字符串s2 是否存在于字符串1中的布尔函数
#!/usr/bin/env python

def compare(s1, s2, n):
for i in range(len(s2)):
if s2[i] != s1[n+i]:
return False
return True

a="abcdefghi"
b="cde"

x = compare(a,b,2)
print x


如果用JAVA实现
private static boolean compare(ByteBuffer MM, byte[] a, int pos) {
for (int j = 0; j < a.length; ++j) {
if (a[j] != MM.get(pos + j))     { return false;     }
}
return true;
}
import java.io.*;
import java.nio.*;
import java.nio.channels.*;

public class stub {

//string to find
private static final String CRLF = "\n";
private static final String FIND = CRLF + "FromP26";

//entry point
public static void main (String args[]) {
if (args.length != 1) {
System.out.println("use: java stub <bigtextfile>");
System.exit(0);
}
parse(args[0]);
}

//tool fct: compare byte to byte
private static boolean compare(MappedByteBuffer MM, byte[] a, int pos) {
for (int j = 0; j < a.length; ++j) {
if (a[j] != MM.get(pos + j))     { return false;     }
}
return true;
}

//parse fct
private static void parse(String file) {

RandomAccessFile in = null;
FileChannel rwChannel = null;
MappedByteBuffer MM = null;

long channelsize = 0;

try {
//create a readwrite channel (i must truncate the file after)
in = new RandomAccessFile(file, "rw");
rwChannel = in.getChannel();
channelsize = rwChannel.size();
MM = rwChannel.map(FileChannel.MapMode.READ_WRITE, 0, channelsize);
}  catch(Exception e) {
System.out.println("unchecked exception");
System.exit(0);
}

byte[] find = FIND.getBytes();

long lastpos = 0;
int size = 0;

for (int pos = 0; pos <= channelsize - find.length; ++pos) {
//System.out.println(channelsize);
if (compare(MM, find, pos)) {

//position found!
pos += 1;
lastpos = pos+find.length-1;
display_result(MM, pos , lastpos);
}
//fetch next

}
}
private static void display_result (MappedByteBuffer mm, long start, long end) {

int size = (int)(end-start);

//byte array
byte[] b = new byte[size];

//copy from memorymapped to local byte array
for (int i = 0; i < size; i++) {
b[i] = mm.get( ((int)start) + i);
}

//conversion
String s1 = null;
try { s1 = new String(b, 0, size, "ASCII"); }
catch (Exception e) { System.exit(0); }

//do not ouput garbage :)
System.out.println("read: \n" + s1);
}
}


参考: https://community.oracle.com/thread/1809441
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: