開発環境
- Microsoft Windows 8 Pro 64bit 日本語 (OS)
- Microsoft Visual Studio Express 2012 for Windows Desktop (IDE)
- プログラミング言語: C#
『初めてのC# 第2版』(Jesse Liberty+Brian MacDonald著、日向俊二訳、オライリー・ジャパン、2006年、ISBN978-487312-194-7)の 第15章(文字列)15.6(練習問題)練習15-2を解いてみる。
その他参考書籍
練習15-2.
コード
using System; using System.Text; using System.Text.RegularExpressions; class Tester { public void Run() { string text = "We hold these truths to be self-evident, " + "that all men are created equal, " + "that they are endowed by their Creator with certain unalienable Rights, " + "that among these are Life, Liberty and the pursuit of Happiness."; StringBuilder sBuilder = new StringBuilder(); Regex reg = new Regex(" |, |,"); int i = 0; foreach (string s in reg.Split(text)) { sBuilder.AppendFormat("{0}: {1}\n", i, s); i += 1; } Console.WriteLine(sBuilder); } static void Main() { Tester t = new Tester(); t.Run(); } }
入出力結果(Console Window)
0: We 1: hold 2: these 3: truths 4: to 5: be 6: self-evident 7: that 8: all 9: men 10: are 11: created 12: equal 13: that 14: they 15: are 16: endowed 17: by 18: their 19: Creator 20: with 21: certain 22: unalienable 23: Rights 24: that 25: among 26: these 27: are 28: Life 29: Liberty 30: and 31: the 32: pursuit 33: of 34: Happiness. 続行するには何かキーを押してください . . .
ちなみにJavaScriptの場合。
コード(BBEdit)
var text = "We hold these truths to be self-evident, " + "that all men are created equal, " + "that they are endowed by their Creator with certain unalienable Rights, " + "that among these are Life, Liberty and the pursuit of Happiness."; var result = ""; var i = 0; var pattern = /\b(\w+)\b/g; var s; while ((s = pattern.exec(text)) !== null) { result += i + ": " + s[0] + "\n"; i += 1; } $('#pre0').text(result);
pythonの場合。
sample.py
コード(BBEdit)
#!/usr/bin/env python3.3 # -*- coding: utf-8 -*- import re text = "We hold these truths to be self-evident, " + \ "that all men are created equal, " + \ "that they are endowed by their Creator with certain unalienable Rights, " + \ "that among these are Life, Liberty and the pursuit of Happiness." i = 0 for word in re.findall(r"\b\w+\b", text): print("{0}: {1}".format(i, word)) i += 1
入出力結果(Terminal)
$ ./sample.py 0: We 1: hold 2: these 3: truths 4: to 5: be 6: self 7: evident 8: that 9: all 10: men 11: are 12: created 13: equal 14: that 15: they 16: are 17: endowed 18: by 19: their 20: Creator 21: with 22: certain 23: unalienable 24: Rights 25: that 26: among 27: these 28: are 29: Life 30: Liberty 31: and 32: the 33: pursuit 34: of 35: Happiness $
0 コメント:
コメントを投稿