2012年11月6日火曜日

開発環境

『初めてのC# 第2版』(Jesse Liberty+Brian MacDonald著、日向俊二訳、オライリー・ジャパン、2006年、ISBN978-487311-294-7)の 第15章(文字列)15.6(練習問題)練習15-2を解いてみる。

その他参考書籍

練習15-2.

コード

using System;
using System.Text;
using System.Text.RegularExpressions;

class Tester
{
    public void Run()
    {
        string str = "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 = 1;
        foreach (string item in reg.Split(str))
        {
            sBuilder.AppendFormat("{0}: {1}\n", i, item);
            i++;
        }
        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: and
32: the
33: pursuit
34: of
35: Happiness.

続行するには何かキーを押してください . . .

ちなみにJavaScriptの場合。

コード(TextWrangler)

var str = "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 strs = str.split(/,|, | /);
var result = "";
for(var i = 0 ; i < strs.length; i++){
  result += (i + 1) + ": " + strs[i] + "\n";
}
$('#pre0').text(result);


pythonの場合。

sample.py

コード(TextWrangler)

#!/usr/bin/env python3.3
#-*- coding: utf-8 -*-

import re

str = "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.";

reg = re.compile(",|, | ")
i = 1
result = ""
for substr in reg.split(str):
 result += "{0}: {1}\n".format(i, substr)
 i += 1

print(result)

入出力結果(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: and
32: the
33: pursuit
34: of
35: Happiness.

$

0 コメント:

コメントを投稿