2022년 2월 1일 화요일

C# 기본실습문제, 속성, 생성자, StringBuilder

 



C# 기본실습문제, 속성, 생성자, StringBuilder



C# 기본실습문제, 속성, 생성자,StringBuilder1. Sample 클래스는 public Length 속성을 가지고 get, set 접근자를 가지고 있다. 아래 코드중 정상적으로 돟작하는것은? a. Sample.Length = 20; b. Sample m = new Sample(); m.Length = 10; c. Console.WriteLine(S…

ojc.asia



  • 0열 선택0열 다음에 열 추가
  • 0행 선택0행 다음에 행 추가
셀 전체 선택
열 너비 조절
행 높이 조절
C# 기본실습문제, 속성, 생성자, StringBuilder


1. Sample 클래스는 public Length 속성을 가지고 get, set 접근자를 가지고 있다. 아래 코드중 정상적으로 돟작하는것은?


a. Sample.Length = 20;


b. Sample m = new Sample();


m.Length = 10;


c. Console.WriteLine(Sample.Length);


d. Sample m = new Sample();


int len;


len = m.Length;


e. Sample m = new Sample();


m.Length = m.Length + 20;






정답 : b, d, e






2. Sample 클래스의 쓰기전용 일반속성 Length를 구현하세요.(Sample 클래스 작성)


[정답]


class Sample


{


int len;


public int Length


{


set


{


len = value;


}


}


}






3. 괄호를 채우세요.


using System;


class EnumPropertyExam


{


DayOfWeek _day;


public DayOfWeek Day


{


get


{


// 금요일인 경우 예외발생


if ( )


{


throw new Exception("Invalid access");


}


return this._day;


}


set


{


this._day = value;


}


}


}






class Program


{


static void Main()


{


EnumPropertyExam example = new EnumPropertyExam();


example.Day = DayOfWeek.Monday;


Console.WriteLine(example.Day == DayOfWeek.Monday);


example.Day = DayOfWeek.Friday;


Console.WriteLine(example.Day);


}


}


/* 결과 :


True






처리되지 않은 예외: System.Exception: Invalid access


위치: EnumPropertyExam.get_Day() 파일 C:\GitHub\csharp20181230\PropertyTest2\PropertyTest2\Program.cs:줄 12


위치: Program.Main() 파일 C:\GitHub\csharp20181230\PropertyTest2\PropertyTest2\Program.cs:줄 31


*/






//정답 : this._day == DayOfWeek.Friday






4. 사용자로 부터 두수를 입력받아 그사이의 소수의 합을 출력하세요.


using System;




class Program
{
static void Main()
{
int a, b, max, min, i, count, totalsum;


Console.WriteLine("두수를 입력하세요.");
Console.WriteLine("예 : 3,5");
string str = Console.ReadLine();
str.Trim();
string[] strarr = str.Split(',');
if (strarr.Length != 2)
{
Console.WriteLine("숫자2개를 콤마로 구분해서 입력하세요~");
return;
}


a = int.Parse(strarr[0]);
b = int.Parse(strarr[1]);




if (a < b)
{
max = b;
min = a;


}
else
{
max = a;
min = b;
}
i = min;
totalsum = 0;


for (int k = min; k <= max; k++)
{
count = 0;
for (int l = 2; l <= k; l++)
{
if (k % l == 0)
{
count++;
}
}


if (count == 1)
{
totalsum += k;
}
}


Console.WriteLine(totalsum);


}
}








5. 아래 예문에서 기본 생성자를 삭제해도 똑같은 결과를 낼수 있도록 코드를 수정하세요.






using System;






namespace ConstructorTest2


{


class Emp


{


string name;


//기본생성자, new할때 호출, 객체를 초기화


public Emp() {


name = "홍길이";


Console.WriteLine("EMP 객체생성..." + name);


}


public Emp(string name) //생성자, 생성자 오버로딩


{


this.name = name;


Console.WriteLine("EMP 객체생성..." + name);


}


}


class EmpTest


{


static void Main(string[] args)


{


Emp e = new Emp();


Emp e1 = new Emp("광개토");


}


}


}


[정답]


//public Emp(string name = "홍길이")






6. 실행결과를 참조하여 괄호를 채우세요.






using System;






public class Emp


{


( 1 )


}


public class ToStringMethod


{


static void Main()


{


Emp e = new Emp();


( 2 ) o = ( 3 ) ;






Console.WriteLine(o.ToString());


Console.WriteLine(e.ToString());


Console.WriteLine(e);


}


}


//결과


System.Object


This is Emp class


This is Emp class






[정답]


public override string ToString()


{


return "This is Emp class";


}






object


object






7. 1부터 10000까지 7은 모두 몇번 나오는가? C#으로 코딩 하세요.


[정답]


1. Console.WriteLine(Enumerable.Range(1,10000).Sum(o=>o.ToString().Count(n=>n=='7')));






2. public static void searchSeven(int num) {
if (num % 10 == 7) count++;
if (num > 10) searchSeven(num / 10);
}
3. static void Main()
{
Console.WriteLine("숫자를 입력하세요 :");
string str = "";
str = Console.ReadLine();


int m = 0;
bool parsed = Int32.TryParse(str, out m);
if (!parsed)
{
Console.WriteLine("숫자를 입력하세요");
Environment.Exit(0);
}


int input = Convert.ToInt32(str);
int hap = 0; int i = 0; int num = 0;
string Word = "7";
for (i = 1; i <= input; i++)
{
str = Convert.ToString(i);
num = str.Length - str.Replace(Word, "").Length;
hap = hap + num;
}
Console.WriteLine("7의 총 개수: {0}", hap);
}






8. c:\GitHub 폴더에 number.txt 파일을 만들고 숫자를 1부터 100까지를 한라인씩


100줄에 입략한 후 이를 C# 응용프로그램에서 읽어서 합을 구하세요.






[정답]


using System;
using System.IO;
namespace ReadLineFromFile{
class Program {
static void Main(string[] args)
{
int sum = Sum(@"c:\GitHub\number.txt");
Console.WriteLine($"{sum}");
}
static int Sum( string file )
{
int sum = 0;
string[] arr = File.ReadAllLines(file);
foreach (string s in arr) sum += Int32.Parse(s);
return sum;
}
}
}






9. String과 StringBuilder의 차이점에 대해 설명하고 예제를 작성하세요.


[정답]


String은 Immutable 즉 한번 문자열을 지정하고 객체를 생성했으면, 더이상 문자열을 수정할 수 없게 된다. Mutable 타입인 StringBuilder는 이와 반대의 경우로 객체 생성이후에도 문자열을 수정할 수 있다.






예를 들어, 아래의 코드는 1부터 10000까지 숫자를 string 변수에 연속해서 추가하는 예이다.






string s = string.Empty;


for(int i=1; i<=10000; i++)


{


s += i.ToString();


}


이 코드의 문제점은 string변수 s에 숫자를 추가할 때, 해당 변수 s의 값을 수정하는 것이 아니라 별도의 새 string객체를 만들고(물론 이름은 s로 똑같지만 Heap상의 메모리는 다르다) 이전 s의 문자값을 새로운 문자열 객체에 복사하게 된다는 점이다. 이러한 새 객체 생성및 기존 데이타 복사가 루프에서 만번 일어 나기 때문에 성능은 저하되고 필요 이상의 많은 메모리를 쓰게 된다.






이러한 문제점을 막기 위해 string 대신 StringBuilder를 사용한다. StringBuilder는 새로운 객체를 생성하지 않고 자신의 내부 버퍼 값만 변경함으로써 값을 추가하게 된다. 따라서 불필요한 객체 생성과 매번 일어나는 데이타 복사 과정이 없어지게 된다. (주: StringBuilder도 해당 객체의 버퍼 용량(Capacity)을 넘는 데이타가 들어올 경우 새로운 버퍼를 현재 Capacity의 2개 크기로 재할당하고 기존 데이타를 복사하게 된다.)






StringBuilder sb = new StringBuilder();


for (int i = 1; i <= 10000; i++)


{


sb.Append(i);


}


string s = sb.ToString();






10. 문자배열에서 중복되지 않는 첫 문자를 리턴하는 함수를 작성하시오. 예를 들어, 입력 문자배열이 abcabdefe 일 때, 중복되지 않는 첫 문자 c 를 리턴함.


[정답]


1.


void RunTest()


{


string s = "abcabdefe";


char ch = GetFirstChar(s.ToCharArray());


Console.WriteLine(ch);


}






char GetFirstChar(char[] S)


{


Dictionary<char, int=""> ht = new Dictionary<char, int="">();</char,></char,>






foreach (char ch in S)


{


if (!ht.ContainsKey(ch))


ht[ch] = 1;


else


ht[ch] += 1;


}






foreach (char ch in S)


{


if (ht[ch] == 1)


return ch;


}






return '\0';


}






2.






using System;


namespace DupTest
{
class Program {
static void Main(string[] args)
{
string s = "abcababcd";
Console.WriteLine(DupCheck(s));
}
static char DupCheck(string s)
{
int cnt;
for (int i = 0; i < s.Length; i++)
{
cnt = CharCnt(s, s[i]);
if (cnt == 1) return s[i];
}
return '\0';
}
static int CharCnt(string s, char c)
{
string[] StringArray = s.Split(new char[] { c }, StringSplitOptions.None);
return StringArray.Length - 1;
}
}
}




3. string inStr1 = "abcabdefe";
char[] Array = inStr1.ToCharArray();
string result = "";
for (int i = 0; i < inStr1.Length; i++)
{
if (inStr1.Length - inStr1.Replace(Array[i].ToString(), "").Length == 1)
{
result = Array[i].ToString();
i = inStr1.Length - 1;
}
}
Console.WriteLine(result);














  • 셀 병합
  • 행 분할
  • 열 분할
  • 너비 맞춤
  • 삭제




http://ojc.asia/bbs/board.php?bo_table=LecCsharp&wr_id=406


C# 기본실습문제, 속성, 생성자, StringBuilder

C# 기본실습문제, 속성, 생성자,StringBuilder1. Sample 클래스는 public Length 속성을 가지고 get, set 접근자를 가지고 있다. 아래 코드중 정상적으로 돟작하는것은? a. Sample.Length = 20; b. Sample m = new Sample(); m

ojc.asia


C# 기본실습문제, 속성, 생성자,StringBuilder1. Sample 클래스는 public Length 속성을 가지고 get, set 접근자를 가지고 있다. 아래 코드중 정상적으로 돟작하는것은? a. Sample.Length = 20; b. Sample m = new Sample(); m.Length = 10; c. Console.WriteLine(S…

ojc.asia



  • 0열 선택0열 다음에 열 추가
  • 0행 선택0행 다음에 행 추가
셀 전체 선택
열 너비 조절
행 높이 조절
C# 기본실습문제, 속성, 생성자, StringBuilder


1. Sample 클래스는 public Length 속성을 가지고 get, set 접근자를 가지고 있다. 아래 코드중 정상적으로 돟작하는것은?


a. Sample.Length = 20;


b. Sample m = new Sample();


m.Length = 10;


c. Console.WriteLine(Sample.Length);


d. Sample m = new Sample();


int len;


len = m.Length;


e. Sample m = new Sample();


m.Length = m.Length + 20;






정답 : b, d, e






2. Sample 클래스의 쓰기전용 일반속성 Length를 구현하세요.(Sample 클래스 작성)


[정답]


class Sample


{


int len;


public int Length


{


set


{


len = value;


}


}


}






3. 괄호를 채우세요.


using System;


class EnumPropertyExam


{


DayOfWeek _day;


public DayOfWeek Day


{


get


{


// 금요일인 경우 예외발생


if ( )


{


throw new Exception("Invalid access");


}


return this._day;


}


set


{


this._day = value;


}


}


}






class Program


{


static void Main()


{


EnumPropertyExam example = new EnumPropertyExam();


example.Day = DayOfWeek.Monday;


Console.WriteLine(example.Day == DayOfWeek.Monday);


example.Day = DayOfWeek.Friday;


Console.WriteLine(example.Day);


}


}


/* 결과 :


True






처리되지 않은 예외: System.Exception: Invalid access


위치: EnumPropertyExam.get_Day() 파일 C:\GitHub\csharp20181230\PropertyTest2\PropertyTest2\Program.cs:줄 12


위치: Program.Main() 파일 C:\GitHub\csharp20181230\PropertyTest2\PropertyTest2\Program.cs:줄 31


*/






//정답 : this._day == DayOfWeek.Friday






4. 사용자로 부터 두수를 입력받아 그사이의 소수의 합을 출력하세요.


using System;




class Program
{
static void Main()
{
int a, b, max, min, i, count, totalsum;


Console.WriteLine("두수를 입력하세요.");
Console.WriteLine("예 : 3,5");
string str = Console.ReadLine();
str.Trim();
string[] strarr = str.Split(',');
if (strarr.Length != 2)
{
Console.WriteLine("숫자2개를 콤마로 구분해서 입력하세요~");
return;
}


a = int.Parse(strarr[0]);
b = int.Parse(strarr[1]);




if (a < b)
{
max = b;
min = a;


}
else
{
max = a;
min = b;
}
i = min;
totalsum = 0;


for (int k = min; k <= max; k++)
{
count = 0;
for (int l = 2; l <= k; l++)
{
if (k % l == 0)
{
count++;
}
}


if (count == 1)
{
totalsum += k;
}
}


Console.WriteLine(totalsum);


}
}








5. 아래 예문에서 기본 생성자를 삭제해도 똑같은 결과를 낼수 있도록 코드를 수정하세요.






using System;






namespace ConstructorTest2


{


class Emp


{


string name;


//기본생성자, new할때 호출, 객체를 초기화


public Emp() {


name = "홍길이";


Console.WriteLine("EMP 객체생성..." + name);


}


public Emp(string name) //생성자, 생성자 오버로딩


{


this.name = name;


Console.WriteLine("EMP 객체생성..." + name);


}


}


class EmpTest


{


static void Main(string[] args)


{


Emp e = new Emp();


Emp e1 = new Emp("광개토");


}


}


}


[정답]


//public Emp(string name = "홍길이")






6. 실행결과를 참조하여 괄호를 채우세요.






using System;






public class Emp


{


( 1 )


}


public class ToStringMethod


{


static void Main()


{


Emp e = new Emp();


( 2 ) o = ( 3 ) ;






Console.WriteLine(o.ToString());


Console.WriteLine(e.ToString());


Console.WriteLine(e);


}


}


//결과


System.Object


This is Emp class


This is Emp class






[정답]


public override string ToString()


{


return "This is Emp class";


}






object


object






7. 1부터 10000까지 7은 모두 몇번 나오는가? C#으로 코딩 하세요.


[정답]


1. Console.WriteLine(Enumerable.Range(1,10000).Sum(o=>o.ToString().Count(n=>n=='7')));






2. public static void searchSeven(int num) {
if (num % 10 == 7) count++;
if (num > 10) searchSeven(num / 10);
}
3. static void Main()
{
Console.WriteLine("숫자를 입력하세요 :");
string str = "";
str = Console.ReadLine();


int m = 0;
bool parsed = Int32.TryParse(str, out m);
if (!parsed)
{
Console.WriteLine("숫자를 입력하세요");
Environment.Exit(0);
}


int input = Convert.ToInt32(str);
int hap = 0; int i = 0; int num = 0;
string Word = "7";
for (i = 1; i <= input; i++)
{
str = Convert.ToString(i);
num = str.Length - str.Replace(Word, "").Length;
hap = hap + num;
}
Console.WriteLine("7의 총 개수: {0}", hap);
}






8. c:\GitHub 폴더에 number.txt 파일을 만들고 숫자를 1부터 100까지를 한라인씩


100줄에 입략한 후 이를 C# 응용프로그램에서 읽어서 합을 구하세요.






[정답]


using System;
using System.IO;
namespace ReadLineFromFile{
class Program {
static void Main(string[] args)
{
int sum = Sum(@"c:\GitHub\number.txt");
Console.WriteLine($"{sum}");
}
static int Sum( string file )
{
int sum = 0;
string[] arr = File.ReadAllLines(file);
foreach (string s in arr) sum += Int32.Parse(s);
return sum;
}
}
}






9. String과 StringBuilder의 차이점에 대해 설명하고 예제를 작성하세요.


[정답]


String은 Immutable 즉 한번 문자열을 지정하고 객체를 생성했으면, 더이상 문자열을 수정할 수 없게 된다. Mutable 타입인 StringBuilder는 이와 반대의 경우로 객체 생성이후에도 문자열을 수정할 수 있다.






예를 들어, 아래의 코드는 1부터 10000까지 숫자를 string 변수에 연속해서 추가하는 예이다.






string s = string.Empty;


for(int i=1; i<=10000; i++)


{


s += i.ToString();


}


이 코드의 문제점은 string변수 s에 숫자를 추가할 때, 해당 변수 s의 값을 수정하는 것이 아니라 별도의 새 string객체를 만들고(물론 이름은 s로 똑같지만 Heap상의 메모리는 다르다) 이전 s의 문자값을 새로운 문자열 객체에 복사하게 된다는 점이다. 이러한 새 객체 생성및 기존 데이타 복사가 루프에서 만번 일어 나기 때문에 성능은 저하되고 필요 이상의 많은 메모리를 쓰게 된다.






이러한 문제점을 막기 위해 string 대신 StringBuilder를 사용한다. StringBuilder는 새로운 객체를 생성하지 않고 자신의 내부 버퍼 값만 변경함으로써 값을 추가하게 된다. 따라서 불필요한 객체 생성과 매번 일어나는 데이타 복사 과정이 없어지게 된다. (주: StringBuilder도 해당 객체의 버퍼 용량(Capacity)을 넘는 데이타가 들어올 경우 새로운 버퍼를 현재 Capacity의 2개 크기로 재할당하고 기존 데이타를 복사하게 된다.)






StringBuilder sb = new StringBuilder();


for (int i = 1; i <= 10000; i++)


{


sb.Append(i);


}


string s = sb.ToString();






10. 문자배열에서 중복되지 않는 첫 문자를 리턴하는 함수를 작성하시오. 예를 들어, 입력 문자배열이 abcabdefe 일 때, 중복되지 않는 첫 문자 c 를 리턴함.


[정답]


1.


void RunTest()


{


string s = "abcabdefe";


char ch = GetFirstChar(s.ToCharArray());


Console.WriteLine(ch);


}






char GetFirstChar(char[] S)


{


Dictionary<char, int=""> ht = new Dictionary<char, int="">();</char,></char,>






foreach (char ch in S)


{


if (!ht.ContainsKey(ch))


ht[ch] = 1;


else


ht[ch] += 1;


}






foreach (char ch in S)


{


if (ht[ch] == 1)


return ch;


}






return '\0';


}






2.






using System;


namespace DupTest
{
class Program {
static void Main(string[] args)
{
string s = "abcababcd";
Console.WriteLine(DupCheck(s));
}
static char DupCheck(string s)
{
int cnt;
for (int i = 0; i < s.Length; i++)
{
cnt = CharCnt(s, s[i]);
if (cnt == 1) return s[i];
}
return '\0';
}
static int CharCnt(string s, char c)
{
string[] StringArray = s.Split(new char[] { c }, StringSplitOptions.None);
return StringArray.Length - 1;
}
}
}




3. string inStr1 = "abcabdefe";
char[] Array = inStr1.ToCharArray();
string result = "";
for (int i = 0; i < inStr1.Length; i++)
{
if (inStr1.Length - inStr1.Replace(Array[i].ToString(), "").Length == 1)
{
result = Array[i].ToString();
i = inStr1.Length - 1;
}
}
Console.WriteLine(result);














  • 셀 병합
  • 행 분할
  • 열 분할
  • 너비 맞춤
  • 삭제




댓글 없음:

댓글 쓰기

(C#교육동영상)C# ADO.NET 실습 ODP.NET/ODAC 설치 오라클 함수 호출 실습, C#학원, WPF학원, 닷넷학원, 자바학원

  (C#교육동영상)C# ADO.NET 실습  ODP.NET/ODAC 설치  오라클 함수 호출 실습, C#학원, WPF학원, 닷넷학원, 자바학원 https://www.youtube.com/watch?v=qIPU85yAlzc&list=PLxU-i...