Search

'string'에 해당되는 글 3건

  1. 2021.03.17 C# String.format 사용법
  2. 2016.10.28 Java SocketServer control Image, DBConnect, String 1
  3. 2016.03.28 c, cpp, com, atl, stl, vc7 String

C# String.format 사용법

Programming/C,CPP,CS 2021. 3. 17. 14:15 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

String Format for Int [C#]

Integer numbers can be formatted in .NET in many ways. You can use static method String.Format or instance method int.ToString. Following examples show how to align numbers (with spaces or zeroes), how to format negative numbers or how to do custom formatting like phone numbers.

Add zeroes before number

To add zeroes before a number, use colon separator „:“ and write as many zeroes as you want.

[C#]
String.Format("{0:00000}", 15); // "00015" String.Format("{0:00000}", -15); // "-00015"

Align number to the right or left

To align number to the right, use comma „,“ followed by a number of characters. This alignment option must be before the colon separator.

[C#]
String.Format("{0,5}", 15); // " 15" String.Format("{0,-5}", 15); // "15 " String.Format("{0,5:000}", 15); // " 015" String.Format("{0,-5:000}", 15); // "015 "

Different formatting for negative numbers and zero

You can have special format for negative numbers and zero. Use semicolon separator „;“ to separate formatting to two or three sections. The second section is format for negative numbers, the third section is for zero.

[C#]
String.Format("{0:#;minus #}", 15); // "15" String.Format("{0:#;minus #}", -15); // "minus 15" String.Format("{0:#;minus #;zero}", 0); // "zero"

Custom number formatting (e.g. phone number)

Numbers can be formatted also to any custom format, e.g. like phone numbers or serial numbers.

[C#]
String.Format("{0:+### ### ### ###}", 447900123456); // "+447 900 123 456" String.Format("{0:##-####-####}", 8958712551); // "89-5871-2551"

 

 

출처 : www.csharp-examples.net/string-format-int/

 

String Format for Int [C#]

String Format for Int [C#] Integer numbers can be formatted in .NET in many ways. You can use static method String.Format or instance method int.ToString. Following examples show how to align numbers (with spaces or zeroes), how to format negative numbers

www.csharp-examples.net

 

336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

Java SocketServer control Image, DBConnect, String




package com.tistory.tansanc;

import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;

import javax.imageio.ImageIO;

class DBConnect {
	ResultSet rs = null;
	Connection conn = null;
	Statement stmt = null;
	public DBConnect() {
		try {
			String url = "jdbc:sqlserver://192.168.10.17:1433;DatabaseName=MSSQLSERVER";
			
			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
			conn = DriverManager.getConnection(url, "sa", "1234");
			stmt = conn.createStatement();
			

		} catch (Exception e) {

		}
	}

	public void finalize() {
		try {
			rs.close();
			stmt.close();
			conn.close();
		} catch (Exception e) {

		}
	}
}

class PerClientThread extends Thread {
	Socket s;
	static ArrayList socketArray = new ArrayList();
	static DBConnect dbc;
	
	public PerClientThread()
	{
		
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub

		socketArray.add(s);
		BufferedReader br;

		
		try {
			br = new BufferedReader(new InputStreamReader(s.getInputStream()));
			String temp;
			while ((temp = br.readLine()) != null) {
				// DB Query
				if (temp.startsWith("select")) {
					
					try {
						dbc.rs = dbc.stmt.executeQuery("SELECT * FROM [dbo].[TESTDB]");

						while (dbc.rs.next()) {
							String field1 = dbc.rs.getString("Date");
							String field2 = dbc.rs.getString("FileName");
							System.out.println(field1);
							System.out.println(field2);

							java.sql.Blob blb = dbc.rs.getBlob("Image");
							byte[] imagebytes = blb.getBytes(0, (int) blb.length());
							BufferedImage theImage = ImageIO.read(new ByteArrayInputStream(imagebytes));

						}
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					temp = "SQL:" + temp;
					System.out.println(temp);
				}
				// Arduino
				else if (temp.startsWith("insert"))
				{
					
				}
				// Arduino
				else if (temp.startsWith("image"))
				{

			        int size = Integer.parseInt(br.readLine());
			        
			        DataInputStream inputStream = new DataInputStream(s.getInputStream());
			        
			        byte[] imageAr = new byte[size];
			        inputStream.read(imageAr, 0, size);

			        BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageAr));

			        System.out.println("Received " + image.getHeight() + "x" + image.getWidth() + ": " + System.currentTimeMillis());
			        ImageIO.write(image, "png", new File("C:\\test2.png"));


				}
				// Arduino
				else if (temp.startsWith("to"))
				{
					
				}
				System.out.print(s.getInetAddress() + " : ");
				System.out.println(temp);
				for (int i = 0; i < socketArray.size(); i++) {
					PrintWriter os = new PrintWriter(socketArray.get(i).getOutputStream(), true);
					os.print(s.getInetAddress() + " : ");
					os.println(temp);
				}
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		super.run();
	}
}

public class Server {
	public static void main(String[] args) throws Exception {
 
		System.out.println("Server Side");
		ServerSocket ss = new ServerSocket(33333);
		Socket s;
		while (true) {
			s = ss.accept();
			PerClientThread pct = new PerClientThread();
			pct.s = s;
			pct.dbc = new DBConnect();
			pct.start();
		}

	}
}










Client.java
package com.tistory.tansanc;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;

class MyFrame extends JFrame {
	public static JTextArea textArea;
	JTextField textField;
	PrintWriter out;
	Socket s;

	public MyFrame() {
		textArea = new JTextArea();
		textField = new JTextField();
		add(BorderLayout.CENTER, textArea);
		add(BorderLayout.SOUTH, textField);
		textField.addActionListener(new FieldListener());
		setSize(300, 200);
		setTitle("채팅프로그램 Client");
		setVisible(true);
		// GUI를 설계한다.
	}

	class FieldListener implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent e) {
			// TODO Auto-generated method stub
			if (textField.getText().compareTo("image") == 0) {

				BufferedImage image;
				ByteArrayOutputStream byteArrayOutputStream = null;
				DataOutputStream os = null;
				try {
					image = ImageIO.read(new File("C:\\test.png"));
					byteArrayOutputStream = new ByteArrayOutputStream();
					ImageIO.write(image, "png", byteArrayOutputStream);
					os = new DataOutputStream(s.getOutputStream());
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
				try {
					int size = byteArrayOutputStream.size();
					out.println("image");
					out.println(size);
					os.write(byteArrayOutputStream.toByteArray());
					os.flush();
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}

			} else {
				out.println(textField.getText());
				textField.setText("");
			}
			// 메세지 보내기
		}
	}
}

class SendThread extends Thread {
	PrintWriter out;

	public SendThread(PrintWriter out) {
		this.out = out;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		super.run();
	}
}

class RecvThread extends Thread {
	BufferedReader in;

	public RecvThread(BufferedReader in) {
		this.in = in;
	}

	@Override
	public void run() {
		String temp;
		try {
			while ((temp = in.readLine()) != null) {

				MyFrame.textArea.setText(MyFrame.textArea.getText() + "\n" + temp);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

class ClientModule {
	MyFrame mFrame;
	SendThread mSendThread;
	RecvThread mRecvThread;
	Socket s;

	// 서버에 패킷을 보내는 Thread
	// 서버로부터 패킷을 받는 Thread
	public ClientModule() // 준비
	{

		try {
			s = new Socket("192.168.10.17", 33333);
			PrintWriter out = new PrintWriter(s.getOutputStream(), true);
			BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
			mFrame = new MyFrame(); // GUI 객체
			mFrame.s = s;
			mFrame.out = out;
			mSendThread = new SendThread(out);
			mRecvThread = new RecvThread(in);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	void start() // 시작
	{
		mSendThread.start();
		mRecvThread.start();
	}
}

public class Client {
	public static void main(String[] args) {
		ClientModule cm = new ClientModule();
		// 초기화 작업
		cm.start();
		// Thread.start();
	}
}





c, cpp, com, atl, stl, vc7 String

Programming/C,CPP,CS 2016. 3. 28. 10:14 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.


. C 자료형

    char (1) , short (2) , int (4) , long (4), float (4) , double (8) , bool 

    문자 : char

    char szName[20] = "kim";


 

2. WIN API 자료형

 

    BYTE (1,unsigned char) , WORD (2,unsigned short) , UNIT (4, unsigned int) , 

    DWORD (4,unsigned long) , LONG (4,long) , BOOL

    문자 : UCHAR (unsigned char)

    핸들 : 대상을 구분하는 4바이트 정수(HWND, HDC 등)

 

    MBCS문자(열)                 유니코드문자(열)           자동매크로문자(열)

    char                                     wchar_t                              TCHAR

    LPSTR(char*)                    LPWSTR(wchar_t*)        LPTSTR

    LPCSTR(const char*)      LPCWSTR                         LPCTSTR

 

    (참조1) 문자열에 대해 그냥 습관적으로 LPTSTR 또는 LPCTSTR 를 써라

    (참조2) 헝가리안명명법 

                   w(WORD) , dw(DWORD) , i(int) , b(BOOL) , ch(문자) , sz(문자열) , h(핸들)

                   cb(바이트수) , a(배열)

 (참조3) OLECHAR(wchar_t), LPOLESTR(LPWSTR), LPCOLESTR(LPCWSTR), OLESTR(x) = _T(x)


 

3. COM 스트링


    BSTR : 문자열길이를 시작전에 저장하고, 이어서 유니코드문자열을 저장하는 방식
                  1> LPCWSTR ->  BSTR : 생성안됨. 생성함수를 이용해야함
                               BSTR bstr = sysAllocString(L"Hi Bob"); // 메모리할당

                              sysFreeString(bstr); // 메모리제거

                  2> BSTR  ->  LPCWSTR : 형변환 가능

 

    VARIANT : 문자열이 들어올때  BSTR과 동일

 

4. CRT(c runtime library) 지원 스트링클래스

 

    _bstr_t : BSTR랩퍼클래스, 메모리할당/제거를 자동으로 수행

                  1> LPCSTR, LPCWSTR  -> _bstr_t 
                               _bstr_t bs1 = "char string";  // 생성

                  2> _bstr_t  ->  LPCSTR, LPCWSTR 
                               LPCSTR psz1 = (LPCSTR)bs1; // 형변환

                  3> _bstr_t  ->  BSTR : 형변환안됨함수이용
                               BSTR bstr = bs1.copy();

                               sysFreeString(bstr);  // BSTR은 사용후 메모리해제를 해야하는 불편이있음..

 

    _variant_t : VARIANT랩퍼클래스, 메모리할당/제거를 자동으로 수행

                  1> LPCSTR, LPCWSTR  -> _variant_t 
                               _variant_t v1 = "char string"; // 생성

                  2> _variant_t  -> _bstr_t  ->  LPCSTR, LPCWSTR 
                               LPCSTR psz1 = (LPCSTR)(_bstr_t)v1;  //형변환

 

5. ATL 지원 스트링클래스

 

    CComBSTR : BSTR랩퍼클래스, 메모리할당/제거를 자동으로 수행

                  1> LPCSTR, LPCWSTR  ->  CComBSTR 

                               CComBSTR bs1 = "char string"; // 생성

                  2> CComBSTR  ->  BSTR   -> LPCWSTR

                               BSTR bstr = (BSTR)bs1;  // 형변환

 

                  (참조) BSTR -> CComBSTR 

                               CComBSTR bs2; bs2.Attach(W2BSTR(L"Bob"))

                              

    CComVariant : VARIANT랩퍼클래스, 메모리할당/제거를 자동으로 수행

                  1> LPCSTR, LPCWSTR  ->  CComVariant 

                               CComVariant bs1 = "char string"; // 생성

                  2> CComVariant  ->  CComBSTR   ->  BSTR   -> LPCWSTR

                               CComBSTR bs2 = bs1.bstrVal;

 

6. STL 스트링

 

    string 

                  1> LPCSTR -> string

                                string  str = "char string"; //생성

                  2> string -> LPCSTR : 형변환 안됨. 함수이용 

                                LPCSTR psz = str.c_str();

    wstring

                   1> LPCWSTR -> wstring

                                wstring  str = "wide char string"; //생성

                  2> wstring -> LPCWSTR : 형변환 안됨. 함수이용 

                                LPCWSTR psz = str.c_str();

 

7. MFC 스트링

 

    CString

                  1> LPCSTR, LPCWSTR  ->  CString 

                                CString  str = "char string"; //생성

                  2> CString  -> LPCTSTR :

                                LPCTSTR  lpsz = (LPCTSTR)str; //형변환

 

                  (참고)  CString  -> LPTSTR :  함수이용

                               LPTSTR lptsz  = str.GetBuffer(0); str.ReleaseBuffer(); //  올바른 사용

                               LPTSTR lptsz  = (LPTSTR)(LPCTSTR)str  //  잘못된 사용

                               CString  -> BSTR  

                               BSTR bstr = str.AllocSysString(); sysFreeString(bstr)

 

8. VC7 스트링

 

    String : .NET에서 새로 정의한 스트링 클래스

                               String* s1 = S"this is nice"; // 생성

                               CString s2(s1); // 형변환


출처 : http://hacheo.egloos.com/3891296