開発環境
- Microsoft Windows 7 Home Premium (OS)
- Microsoft Visual C# 2010 Express Edition (IDE)
- 言語: C#
『初めてのC# 第2版』(Jesse Liberty+Brian MacDonald著、日向俊二訳、オライリー・ジャパン、2006年、ISBN978-487311-294-7)の 第15章(文字列)15.6(練習問題)練習15-1-3を解いてみる。
その他参考書籍
練習15-1-3.
コード
using System;
class Tester
{
public void Run()
{
string str1 = "Hello";
string str2 = "World";
string str3 = @"Come visit us at http://www.LibertyAssociates.com";
string str41 = string.Concat(str1, ", ", str2, "!");
string str42 = str1 + ", " + str2 + "!";
string str5 = "world";
string str61 = string.Copy(str3);
string str62 = str3;
string[] strs = { str1, str2, str3, str41, str42, str5, str61, str62 };
Console.WriteLine("各文字列に文字「H」が含まれているか");
foreach (string item in strs)
{
string msg = item.IndexOf("H") >= 0 ? "含まれている" : "含まれていない";
Console.WriteLine("{0}: {1}", item, msg);
}
}
static void Main()
{
Tester t = new Tester();
t.Run();
}
}
入出力結果(Console Window)
各文字列に文字「H」が含まれているか Hello: 含まれている World: 含まれていない Come visit us at http://www.LibertyAssociates.com: 含まれていない Hello, World!: 含まれている Hello, World!: 含まれている world: 含まれていない Come visit us at http://www.LibertyAssociates.com: 含まれていない Come visit us at http://www.LibertyAssociates.com: 含まれていない 続行するには何かキーを押してください . . .
ちなみにJavaScriptの場合。
コード(TextWrangler)
var str1 = "Hello";
var str2 = "World";
var str3 = "Come visit us at http://www.LibertyAssociates.com";
var str41 = str1.concat(", ", str2, "!");
var str42 = str1 + ", " + str2 + "!";
var str5 = "world";
var str6 = str3;
var strs = [str1, str2, str3, str41, str42, str5, str6];
var result = "各文字列に文字「H」が含まれているか\n";
for(var i = 0; i < strs.length; i++){
var msg = strs[i].indexOf("H") >= 0 ? "含まれている" : "含まれていない";
result += strs[i] + ": " + msg + "\n";
}
$('#pre0').text(result);
pythonの場合。
sample.py
コード(TextWrangler)
#!/usr/bin/env python3.3
#-*- coding: utf-8 -*-
str1 = "Hello"
str2 = "World"
str3 = """Come visit us at http://www.LibertyAssociates.com"""
str4 = str1 + ", " + str2 + "!"
str5 = "world"
str6 = str3
strs = [str1, str2, str3, str4, str5, str6]
print("各文字列の3番目の文字")
for str in strs:
msg = "含まれている" if str.find("H") >= 0 else "含まれていない"
print("{0}: {1}".format(str, msg))
入出力結果(Terminal)
$ ./sample.py 各文字列の3番目の文字 Hello: 含まれている World: 含まれていない Come visit us at http://www.LibertyAssociates.com: 含まれていない Hello, World!: 含まれている world: 含まれていない Come visit us at http://www.LibertyAssociates.com: 含まれていない $
Pythonは三項演算子(? :)ないみたい。かわりに(A = B if C(評価式) else Z
0 コメント:
コメントを投稿