String & Integer Class Methods

Sungju Kim·2024년 8월 11일

Sparta_Coding_Camp_TIL

목록 보기
13/53

String

Length

int len = str.length();

Indexing of char

char ch = str.charAt(0);

Substring

String sub = str.substring(1, 4);

indexOf

Finds the first occurrence of a specified character or substring in the string.

int index = str.indexOf("abc");

lastIndexOf

Finds the last occurrence of a specified character or substring in the string.

int lastIndex = str.lastIndexOf("abc");

split

Split the string according to the seperator and put it in an array.

String[] parts = str.split(",");

toCharArray

char[] chars = str.toCharArray();

seplace

Replaces all occurrences of the target sequence with the replacement sequence.

String newStr = str.replace("a", "b");

equals

boolean isEqual = str1.equals(str2);

// without looking at upper or lower case
boolean isEqualIgnoreCase = str1.equalsIgnoreCase(str2);

removes leading & trailing white space

String trimmed = str.trim();

startsWith(String prefix) & endsWith(String suffix)

Checks if the string starts or ends with the specified prefix/suffix.

boolean starts = str.startsWith("abc");
boolean ends = str.endsWith("xyz");

Integer

parseInt

Converts a string to an int.

int num = Integer.parseInt("123");

valueOf

Converts string to an Integer object.

Integer num = Integer.valueOf("123");

toString

Converts int to a string

String str = Integer.toString(123);

compare two integers

Integer.compare(a,b)

  • if 'a<b' : return -1
  • if 'a=b' : return 0
  • if 'a>b' : return 1
int result = Integer.compare(5, 10); // returns negative because 5 < 10

max & min

int max = Integer.max(5, 10);
int min = Integer.min(5, 10);

sum

int sum = Integer.sum(5, 10);
profile
Fully ✨committed✨ developer, always eager to learn!

0개의 댓글