python和JAVA之for循环的区别
2016-06-01 15:36
555 查看
写C和JAVA的for循环多了,把python的For循环语句都快忘了。
一个判断字符串s2 是否存在于字符串1中的布尔函数
如果用JAVA实现
参考: https://community.oracle.com/thread/1809441
一个判断字符串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
相关文章推荐
- python之threading
- 用PDB库调试Python程序
- Python注释
- 面向对象基础
- 转 Python爬虫入门四之Urllib库的高级用法
- 好消息! 不用再羡慕Python有jupyter 我R也有Notebook了
- Python编程规范
- Python datetime模块使用
- python学习 流程控制语句详解
- 198. House Robber [easy] (Python)
- Python的Web Services客户端
- python kivy for GUI design
- 转 Python爬虫入门三之Urllib库的基本使用
- 345. Reverse Vowels of a String [easy] (Python)
- Python基本运算符
- qpython3 读取安卓lastpass Cookies
- 【转】Python Anaconda简介及安装
- python基础(2)
- xgboost在window安装----免编译步骤
- unable to find vcvarsall.bat python3.5