開発環境
- 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 s = "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 nd the pursuit of Happiness."; StringBuilder sBuilder = new StringBuilder(); Regex regEx = new Regex(@", |,| "); int i =1; foreach (string item in regEx.Split(s)) { sBuilder.AppendFormat("{0}: {1}\n", i, item); i += 1; } Console.WriteLine(sBuilder); } static void Main() { Tester t = new Tester(); t.Run(); } }
入出力結果(Console Window)
1: We 2: hold 3: these 4: truths 5: to 6: be 7: self-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: nd 32: the 33: pursuit 34: of 35: Happiness. 続行するには何かキーを押してください . . .
ちなみにJavaScriptの場合。
コード(BBEdit)
var s = "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 nd the pursuit of Happiness.", words = s.split(/, |,| /), result = "", i, max; for (i = 0, max = words.length; i < max; i += 1) { result += (i + 1) + ": " + words[i] + "\n"; } $('#pre0').text(result);
pythonの場合。
コード(BBEdit)
sample.py
#!/usr/bin/env python3.3 #-*- coding: utf-8 -*- import re s = ("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 nd the pursuit of Happiness.") words = re.split(", |,| ", s) i = 1 for word in words: print("{0}: {1}".format(i, word)) i += 1
入出力結果(Terminal)
$ ./sample.py 1: We 2: hold 3: these 4: truths 5: to 6: be 7: self-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: nd 32: the 33: pursuit 34: of 35: Happiness. $
0 コメント:
コメントを投稿