(1)写一个方法根据图书名,查询某本图书是否存在
class Book
{
public string Name { get; set; }
public string Author { get; set; }
public float Price { get; set; }
public int PageCount { get; set; }
public Book()
{
}
public Book(string name, string author, float price, int pageCount)
{
Name = name;
Author = author;
Price = price;
PageCount = pageCount;
}
public static bool QuaryBookByBookName(string name,Book[] books)
{
for (int i = 0; i < books.Length; i++)
{
if (name==books[i].Name)
{
return true;
}
}
return false;
}
main方法测试参考代码:
static void Task03()
{
Book[] books = new Book[5];
books[0] = new Book("水浒传","施耐庵",56,560);
books[1] = new Book("C1#从入门到精通", "张三", 78, 1140);
books[2] = new Book("浅谈C#的优与劣", "李四", 98, 540);
books[3] = new Book("红楼梦", "曹雪芹", 42, 780);
books[4] = new Book("C2#从入门到放弃", "王五", 2, 120);
bool ret = Book.QuaryBookByBookName("C#从入门到精通",books);
Console.WriteLine(ret);
ret = Book.QuaryBookByBookName("C#", books);
Console.WriteLine(ret);
ret = Book.QuaryContainsName("C#",books);
Console.WriteLine(ret);
}
(2)写一个方法找出所有包含“C#”字样的图书
public static bool QuaryContainsName(string name,Book[] books)
{
for (int i = 0; i < books.Length; i++)
{
//第一种方式
//if (books[i].Name.Contains(name))
//{
// return true;
//}
//第二种方式
if (IsConctains(books[i].Name,name))
{
return true;
}
}
return false;
}
//判断字符串targetStr中是否包含sourceStr,返回布尔值
static bool IsConctains(string targetStr,string sourceStr)
{
if (targetStr.Length<sourceStr.Length)
{
return false;
}
for (int i = 0; i < targetStr.Length-sourceStr.Length+1; i++)
{
for (int j = 0; j < sourceStr.Length; j++)
{
if (sourceStr[j] != targetStr[i+j])
{
break;
}
if (j==sourceStr.Length-1)
{
return true;
}
}
}
return false;
}
}
main方法测试参考代码:
static void Task03()
{
Book[] books = new Book[5];
books[0] = new Book("水浒传","施耐庵",56,560);
books[1] = new Book("C1#从入门到精通", "张三", 78, 1140);
books[2] = new Book("浅谈C#的优与劣", "李四", 98, 540);
books[3] = new Book("红楼梦", "曹雪芹", 42, 780);
books[4] = new Book("C2#从入门到放弃", "王五", 2, 120);
bool ret = Book.QuaryContainsName("C#",books);
Console.WriteLine(ret);
}