문자열

 

hello world같은 글을 문자열이라고 한다.
문자열을 사용할땐 string을 include해서 사용한다.
string은 기본자료형이 아닌 사람들이 만들어 놓은 사용자 정의 자료형으로 생각하면된다.
다른 기본자료형처럼 =,(),{}방식으로 정의가 가능하다.
숫자가 입력가능하지만 정수형이 아닌 문자형 ""으로 입력해야한다.
입력받을땐 다른 자료형과 같이 cin사용하는 것이 아닌 std::getline(std::cin,str);을 사용한다.
정수형(int)을 입력받고 std::getline(std::cin,str);을 사용하면 기존 버퍼에 남아있던 정수가 출력된다.
std::cin.ignore(32767,'\n');
std::cin.ignore(std::numeric_limits::max(), '\n');
을 이용해 정수입력이후 문자열을 입력받을 수 있다.
+,+=로 문자열에 문자열을 추가해줄 수 있다. append라고한다.
문자열 길이는 .length()로 확인할 수 있다.
string 문자열은 마지막에 문장마무리표시가 들어가있어 길이 1이 추가된다.

 

#include <iostream>
#include <string>
#include <limits>

using namespace std;

int main()
{
	//문자열을 출력한다.
	//아래글자는 char[12]로 출력된다.
	cout << "hello world" << endl;

	int age = 0;
	cin >> age;
	cout << age << endl;
	//cin 버퍼 초기화
	std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
	const string str = "hello world";
	cout << str << endl;
	//숫자입력
	string num = "123";


	string num2 = "";
	//문자열 입력
	std::getline(std::cin, num);
	std::getline(std::cin, num2);

	//문자열 더하기(append)
	cout << num + num2 << endl;
	num += "test";

	//문자열 길이
	cout << num.length() << endl;
	return 0;
}

String 생성 방법의 차이

1. String s1 = new String("Java");

2. String s2 = "Java"; <-리터럴방식

1번 방식으로 생성하게 되면 힙메모리에 올라가게된다.

2번 방식으로 생성하게되면 자바1.7이후 힙메모리안 StringPool이라는 특정메모리안에 올라가게된다.

2번 방식은 값이 같을 경우 같은 주소를 보게된다.


즉, == 로 비교하게되면 주소값을 비교하게되는데 2번방식으로 생성할때만 비교할 수 있다.

.equals()방식은 문자열을 비교하는 것이기 때문에 모두 가능하다.


즉, new()로 생성하면 힙메모리에 생성되고 ""로 생성하게되면 힙메모리안 StringPool에 생성되어 재사용가능하다.



String,StringBuffer,StringBuilder의 차이


String은 불가변적이다.

StringBuffer,StringBuilder은 가변적이다.


String 객체는 Heap메모리에 생성되면 변하지않는다.

변경하게되면 새로운 객체를 생성해야한다.

ex)

String s = "a";

s = s + "b";


String 는 객체(Heap메모리) s는 reference 값(Stack메모리)이다.

String s = "a";

s(reference값)은 Heap 메모리의 "a"의 주소값을 보고 있다.


s = s + "b"; 를 하게되면 

s(reference값)가 보고있는 "a"값에 "b"를 추가하는것이아닌

"ab"라는 객체를 다시만들고 그 객체의 reference값으로 바꾼다.


ex)StringBuffer ,StringBuilder 동일하다.

StringBuffer s = new StringBuffer("a");

s.append("b");


StringBuilder,StringBuffer 는 객체(Heap메모리) s는 reference 값(Stack메모리)이다.

차이점은 StringBuilder,StringBuffer는 객체를 새로 생성하지않고

기존 객체에 값을 추가한다.


개발시에 문자열 병합이 빈번하게 일어나면 StringBuilder,StringBuffer를 사용하는게 좋다.


StringBuilder,StringBuffer 차이는?


synchronization(동기화)지원여부의 차이다.


synchronization란?

하나에 제한되어있는 데이터를 여러 스레드가 공유가 사용할때

데이터가 깨지지않게 줄을세워 키를 가지고 있는 데이터를 처리하고 나머지데이터는 대기시킨다.

데이터무결성을 보장할 수 있다.


StringBuffer는 동기화를 지원하고

StringBuilder는 동기화를 지원하지 않는다.


멀티스레드를 사용하지 않는다면 

StringBuffer보단 StringBuilder가 빠르다.


자바 개발할때 유용한 라이브러리(library)!


StringUtils - 문자열에 작업하는 관련기능들을 모아놓은 Library


사용방법 

1.직접 다운 : 다운로드페이지(click)

2.Maven : MavenRepository페이지(click)

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->

<dependency>

    <groupId>org.apache.commons</groupId>

    <artifactId>commons-lang3</artifactId>

    <version>3.8</version>

</dependency>


직접 다운로드할시 lib에 추가하여 사용하고 Maven사용시엔 pom.xml에 추가한다.


StringUtils.mid("문자열",시작위치,가져올길이)
문자열을 입력된 시작위치에서 가져올길이 만큼가져온다
String mid = StringUtils.mid("showmethemoney", 4, 5);
System.out.println(mid);
//출력결과 : methe

StringUtils.normalizeSpace("문자열")
문자열의 앞뒤 공백을 제거하고 중간에 여러 공백문자를 제거한다.
String normalizeSpace = StringUtils.normalizeSpace("show \tme the money");
System.out.println(normalizeSpace);
//출력결과 : show me the money
StringUtils.ordinalIndexOf("문자열","찾을문자열",카운트수)
문자열에서 찾을문자열을 찾고 카운트하다 카운수에 만족한 위치를 반환한다.
null이거나 카운트수에 만족한 문자가 없을경우 -1을 반환한다.
int ordinalIndexOf = StringUtils.ordinalIndexOf("abcabcabcabc", "abc", 3);
System.out.println(ordinalIndexOf);
//출력결과 : 6
StringUtils.overlay("문자열","넣을문자열",시작위치, 끝위치)
문자열안에 시작위치부터 끝위치전까지 넣을 문자열로 변환한다.
String overlay = StringUtils.overlay("0123456789", "**", 2, 7);
System.out.println(overlay);
//출력결과 : 01**789

StringUtils.prependIfMissing("문자열","접두사","부가접두사")
문자열이 접두사나 부가접두사로 시작하지 않을경우 접두사를 추가한다.
String prependIfMissing = StringUtils.prependIfMissing("Show", "me", "the");
System.out.println(prependIfMissing);
//출력결과 : meShow

StringUtils.prependIfMissing("문자열","접두사","부가접두사")
문자열이 접두사나 부가접두사로 시작하지 않을경우 접두사를 추가한다.(대/소문자를 구분안한다)
String prependIfMissingIgnoreCase = StringUtils.prependIfMissingIgnoreCase("Show", "me", "show");
System.out.println(prependIfMissingIgnoreCase);
//출력결과 : Show
StringUtils.remove("문자열","제거할문자")
문자열안에 제거할 문자가 있을경우 제거하여 반환한다(반복가능).
String remove = StringUtils.remove("s**h**o**w", "**");
System.out.println(remove);
//출력결과 : show

StringUtils.removeAll("문자열","정규식")
문자열안에 정규식에 포함하는 문자가 있을경우 제거하여 반환한다.
String removeAll = StringUtils.removeAll("showMETHEMONEY", "[A-Z]");
System.out.println(removeAll);
//출력결과 : show

StringUtils.removeEnd("문자열","제거할문자")
문자열 마지막에 제가할문자가 있을경우 제거한다.
String removeEnd = StringUtils.removeEnd("showME","ME");
System.out.println(removeEnd);
//출력결과 : show

StringUtils.removeEndIgnoreCase("문자열","제거할문자")
문자열 마지막에 제가할문자가 있을경우 제거한다.(대/소문자를 구분안한다)
String removeEndIgnoreCase = StringUtils.removeEndIgnoreCase("showME", "me");
System.out.println(removeEndIgnoreCase);
//출력결과 : show

StringUtils.removeFirst("문자열","정규식")
문자열안에 정규식에 포함하는 문자가 있을경우 첫번째를 제거하여 반환한다.
String removeFirst = StringUtils.removeFirst("<test>show", "<.*>");
System.out.println(removeFirst);
//출력결과 : show

StringUtils.removeIgnoreCase("문자열","제거할문자")
문자열안에 제거할 문자가 있을경우 제거하여 반환한다(반복가능).(대/소문자를 구분안한다)
String removeIgnoreCase = StringUtils.removeIgnoreCase("sThtotwT", "t");
System.out.println(removeIgnoreCase);
//출력결과 : show



StringUtils.removePattern("문자열","제거할패턴")
문자열안에 제거할 패턴이 있을경우 패턴안의 내용까지 제거후 반환한다.
String removePattern = StringUtils.removePattern("<test>\n<test>show", "<.*>");
System.out.println(removePattern);
//출력결과 : show

StringUtils.removeStart("문자열","제거할문자")
문자열안에 첫번쨰 제거할 문자를 제거한 후 반환한다.
String removeStart = StringUtils.removeStart("showshow", "show");
System.out.println(removeStart);
//출력결과 : show
StringUtils.removeStartIgnoreCase("문자열","제거할문자")
문자열안에 첫번쨰 제거할 문자를 제거한 후 반환한다.(대/소문자를 구분안한다)
String removeStartIgnoreCase = StringUtils.removeStartIgnoreCase("showshow", "SHOW");
System.out.println(removeStartIgnoreCase);
//출력결과 : show
StringUtils.repeat("문자열","구분자",반복할숫자)
문자열을 반복할 숫자만큼 반복하여 반환한다.
구분자가 없을경우 그냥 반복하여 반환한다.
String repeat = StringUtils.repeat("show",",", 3);
System.out.println(repeat);
//출력결과 : show,show,show
StringUtils.replace("문자열","찾을문자","변경문자")
문자열에서 찾을 문자열을 찾고 변경문자로 변경하여 반환한다.
String replace = StringUtils.replace("testtest", "test", "show");
System.out.println(replace);
//출력결과 : showshow

StringUtils.replace("문자열","찾을문자","변경문자",변경횟수)
문자열에서 찾을 문자열을 찾고 변경횟수만큼 변경문자로 변경하여 반환한다.
String replace2 = StringUtils.replace("testtest", "test", "show",1);
System.out.println(replace2);
//출력결과 : showtest

StringUtils.replaceAll("문자열","정규식","변경문자")
문자열에서 정규식에 포함되는 문자를 찾고 
변경문자로 변경하여 반환한다.
String replaceAll = StringUtils.replaceAll("SHOWshowSHOW", "[A-Z]", "^");
System.out.println(replaceAll);
//출력결과 : ^^^^show^^^^

StringUtils.replaceChars("문자열","변경할문자","변경문자")
문자열에서 변경할 문자를 한글자씩 찾고 변경문자로 변경한다.
String replaceChars = StringUtils.replaceChars("mhoe", "me", "sw");
System.out.println(replaceChars);
//출력결과 : show
StringUtils.replaceEach("문자열",변경할문자배열,변경문자배열)
문자열에서 변경할 문자배열을 확인후 있으면 변경문자배열로 변경하여 반환한다.
String replaceEach =
StringUtils.replaceEach("methe", new String[]{"me", "the"}, new String[]{"sh", "ow"});
System.out.println(replaceEach);
//출력결과 : show

StringUtils.replaceEachRepeatedly("문자열",변경할문자배열,변경문자배열)
문자열에서 변경할 문자배열을 확인후 그 단어를 변경문자배열에 확인하여
변경문자배열과 겹치지 않은 단어로 변경한다.
쓸일없을거같다.
String replaceEachRepeatedly = 
StringUtils.replaceEachRepeatedly("me", new String[]{"m", "e"}, new String[]{"e", "d"});
System.out.println(replaceEachRepeatedly);
//출력결과 : dd
StringUtils.replaceFirst("문자열","찾을문자열","변경문자")
문자열에서 찾을문자열을 찾아 첫번째를 변경문자로 변경 후 반환한다.(정규식사용가능)
String replaceFirst = StringUtils.replaceFirst("show56show", "show", "1234");
System.out.println(replaceFirst);
//출력결과 : 123456show
StringUtils.replaceFirst("문자열","찾을문자열","변경문자")
문자열에서 찾을문자열을 찾아 변경문자로 변경 후 반환한다.(대/소문자를 구분안한다)
String replaceIgnoreCase = StringUtils.replaceIgnoreCase("Aa", "a", "1");
System.out.println(replaceIgnoreCase);
//출력결과 : 11
StringUtils.replaceOnce("문자열","찾을문자열","변경문자")
문자열에서 찾을문자열을 찾아  한번만 변경문자로 변경 후 반환한다.(정규표현식사용불가)
String replaceOnce = StringUtils.replaceOnce("sshow", "s", "1");
System.out.println(replaceOnce);
//출력결과 : 1show
StringUtils.replaceOnceIgnoreCase("문자열","찾을문자열","변경문자")
문자열에서 찾을문자열을 찾아  한번만 변경문자로 변경 후 반환한다.(대/소문자를 구분안한다,정규표현식사용불가)
String replaceOnceIgnoreCase = StringUtils.replaceOnceIgnoreCase("sshow", "S", "1");
System.out.println(replaceOnceIgnoreCase);
//출력결과 : 1show
StringUtils.replacePattern("문자열","정규식","변경문자")
문자열에서 정규식에 포함되어있는 문자를 변경문자로 변경 후 반환한다.
String replacePattern = StringUtils.replacePattern("<__>test<__>me", "<.*>", "show");
System.out.println(replacePattern);
//출력결과 : showme

StringUtils.reverse("문자열")
문자열을 반대로 변환후 반환한다.
String reverse = StringUtils.reverse("show");
System.out.println(reverse);
//출력결과 : wohs
StringUtils.reverse("문자열",'구분자'(char형태문자))
구분자 기준으로 순서를 반대로 바꾼후 반환한다.
구분자가 아닌 문자는 반대로 변환되지 않는다.
String reverseDelimited = StringUtils.reverseDelimited("123.456.789", '.');
System.out.println(reverseDelimited);
//출력결과 : 789.456.123

StringUtils.right("문자열",가져올크기)
문자열의 오른쪽을 기준으로 가져올크기 만큼 반환한다.
String right = StringUtils.right("show", 2);
System.out.println(right);
//출력결과 : ow
StringUtils.rightPad("문자열",문자크기,"추가할문자")
문자열의 오른쪽에 문자크기만큼 추가할문자를 추가 후 반환한다.
추가할문자가 없을 경우 공백으로 추가 후 반환환다.
String rightPad = StringUtils.rightPad("show", 10, "!@#$");
System.out.println(rightPad);
//출력결과 : show!@#$!@

StringUtils.rotate("문자열",이동할숫자)
문자열을 이동할숫자만큼 이동한다 (양수방향 ->,음수방향<-)
String rotate = StringUtils.rotate("show", 2);
System.out.println(rotate);
//출력결과 : owsh



JAVA  StringUtils 문자열 작업 - 1 보러가기(Click)

java StringUtils 문자열 작업 - 1 Method

String abbreviate ,String appendIfMissing ,String appendIfMissingIgnoreCase ,String capitalize ,String chomp ,String chomp2 ,String chop ,String center ,String center2 ,int compare ,int compareIgnoreCase ,boolean contains ,boolean containsAny ,boolean containsIgnoreCase ,boolean containsNone ,boolean containsOnly ,boolean containsWhitespace ,int countMatches ,String defaultIfBlank ,String defaultIfEmpty ,String defaultString ,String deleteWhitespace ,String difference ,boolean endsWith ,boolean endsWithAny ,boolean endsWithIgnoreCase ,boolean equals ,boolean equalsAny ,boolean equalsAnyIgnoreCase ,boolean equalsIgnoreCase ,String firstNonBlank ,String getCommonPrefix ,String getDigits ,int indexOf ,int indexOfAny ,int indexOfAnyBut ,int indexOfDifference ,int indexOfIgnoreCase 



JAVA  StringUtils 문자열 작업 - 2 보러가기(Click)

java StringUtils 문자열 작업 - 2 Method

boolean isAllBlank ,boolean isAllEmpty ,boolean isAllLowerCase ,boolean isAllUpperCase ,boolean isAlpha ,boolean isAlphanumeric ,boolean isAlphanumericSpace ,boolean isAlphaSpace ,boolean isAnyBlank ,boolean isAnyEmpty ,boolean isAsciiPrintable ,boolean isBlank ,boolean isEmpty ,boolean isMixedCase ,boolean isNoneBlank ,boolean isNoneEmpty ,boolean isNotBlank ,boolean isNotEmpty ,boolean isNumeric ,boolean isNumericSpace ,boolean isWhitespace ,boolean startsWith ,boolean startsWithAny ,boolean startsWithIgnoreCase ,String join ,String joinWith ,int lastIndexOf ,int lastIndexOf2 ,int lastIndexOfAny ,int lastIndexOfIgnoreCase ,int lastIndexOfIgnoreCase2 ,int lastOrdinalIndexOf ,String left ,String leftPad ,int length ,String lowerCase 


JAVA  StringUtils 문자열 작업 - 4 보러가기(Click)

java StringUtils 문자열 작업 - 4 Method

String[] split ,String[] split2 ,String[] splitByCharacterType ,String[] splitByCharacterTypeCamelCase ,String[] splitByWholeSeparator ,String[] splitByWholeSeparatorPreserveAllTokens ,String[] splitPreserveAllTokens ,String[] splitPreserveAllTokens2 ,String strip ,String stripAccents ,String[] stripAll ,String stripEnd ,String stripStart ,String stripToEmpty ,String stripToNull ,String substring ,String substring2 ,String substringAfter ,String substringAfterLast ,String substringBeforeLast ,String substringBetween ,String substringBetween2 ,String[] substringsBetween ,String swapCase ,int[] toCodePoints ,String trim ,String trimToEmpty ,String trimToNull ,String truncate ,String truncate2 ,String uncapitalize ,String unwrap ,String upperCase ,String wrap ,String wrapIfMissing



String 개념

String문자는 ""를 사용해 만들어진다.



위처럼 text란 String을 만들게되면 문자란 값을 상수저장소(Constant pool)에 저장한다.


동일한 "문자" 라는 문자열을 생성할경우


위에 말했듯이 String text를 생성할때 상수저장소에 저장하게되는데

text2가 만들어질때 상수저장소를 확인하고 "문자"가 있을경우 그 참조한 값을 반환한다.

text,text2 참조값은 같다.

그러므로 text와 text2는 같다.


상수저장소란?

- String객체를 저장하는 메모리 구역이다.


즉, 문자열이 이미 존재하면 새로운 객체를 생성하지않고

기존객체를 사용하여 효율적이게된다.


위처럼 new String으로 문자열 생성시 상수저장소에 저장하지않고

일반 힙 메모리에 String객체를 생성한다.

text와 text2의 참조값이 다르다.

text==text2는 될수 없다.


String 비교방법

1.equals() 메소드

2.단순 == 비교

3.compareTo() 메소드


equals() 메소드

equals와 equalsIgnoreCase 있다.


equals이란?

문자열의 내용을 비교하는 것이다.



equalsIgnoreCase이란?

문자열의 특징을 무시하고 비교하는 것(쉽게말해 소문자,대문자)이다.



단순 == 비교

위에 String 개념에서 설명한다.


compareTo() 메소드

문자열 길이를 비교해 정수를 반환해준다.

같다면 0

크다면 1

작다면 -1





변수란?

데이터 타입이다.
primitive type(원시 타입)이라고 불린다.
앞 글자를 소문자로 사용한다.

int <-상수, 소수점을 받아들이지 않는다.
ex) int myInt = 2;

short <- 용량을 작게 차지한다.
(큰 숫자는 안됨)
ex) short myShort = 1;

long <- 큰 숫자에 사용한다.(마지막에 L을 붙임)
ex) long myLong = 1L;

double <- 소수점에 사용한다.
ex) double myDouble = 1.2;

float <- 용량을 작게 차지한다.(특이점 :마지막에 f를 붙인다.)
float myFloat = 1.3f;

char <- 문자열에 사용한다.(특이점:한 글자만 사용 가능하고,''작은따옴표로 사용한다.)
ex) char myChar = 'c';

boolean <- 참, 거짓에 사용한다.(true, false)
ex) boolean myBoolean = false;

byte <- 용량 표현에 사용한다.
ex) byte myByte = 24;

문자열이란?

primitive type(원시 타입) 아니다.
String -> ""사용, 숫자도 문자로 인식한다.
ex) String text = "number : "+myInt;
특이점:뒤에 int형을 문자로 인식한다.

text = myInt; <-X
ex) primitive type 형태만 입력은 안된다.

String 뒤에 숫자 가와도 String으로 인식한다.
primitive type 뒤에 문자열은 안된다.
ex) text = text+": "+myInt;


+ Recent posts