2012年12月20日木曜日

開発環境

『初めてのC# 第2版』(Jesse Liberty+Brian MacDonald著、日向俊二訳、オライリー・ジャパン、2006年、ISBN978-487311-294-7)の 第15章(文字列)14.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.";
        Regex reg = new Regex(@",| |\.");
        StringBuilder sBuilder = new StringBuilder();
        int id = 1;
        foreach (string subStr in reg.Split(str))
        {
            sBuilder.AppendFormat("{0}: {1}\n", id++, subStr);
        }
        Console.WriteLine("{0}", 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
36:

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

ちなみにJavaScriptの場合。

コード(TextWrangler)

var result = "";
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 str_a = str.split(/,| |\./);
for(var i = 0; i < str_a.length; i++){
  result += (i + 1) + ": " + str_a[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."

strs = re.split(r",|\.| ", str)

result = ""
id = 1
for s in strs:
    result += "{0}: {1}\n".format(id, s)
    id += 1

print(result, end="")

入出力結果(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
36: 
$

0 コメント:

コメントを投稿