[skill summary] conversion between java integers, strings and arrays

Posted by blindeddie on Fri, 21 Jan 2022 05:45:41 +0100

Summarizes the common transformation methods between integers, strings and arrays in JAVA, as well as some common usages, which are convenient for reference and review. If you have any questions, you are welcome to leave a message.

1. Integer to string

int number = 123456;
Integer.toString(number);
int number = 123456;
String.valueOf(number);
int number = 123456;
String str = number+"";

2. The string becomes an integer

String s="123456";
int i;
i=Integer.parseInt(s);
String s="123456";
int i;
i=Integer.valueOf(s).intValue();

3. Integer to array

int number = 123456;
char[] array = String.valueOf(number).toCharArray();
for (int i = 0; i < array.length; i++){
	System.out.print(array[i] + " ");
}
int number = 123456;
String[] str = Integer.toString(number).split("");
for(int i = 0; i < str.length; i++){
	System.out.print(str[i] + " ");
}

4. The array becomes an integer

int sum = 0;
int array[] = new int[]{1,2,3,4,5,6};
for(int j = 0; j <= array.length - 1; j++){
	sum = sum * 10 + array[j];
}

5. The string becomes an array

String s = "123abc I love you!";
char[] array = new char[s.length()];
for(int i = 0; i < s.length(); i++){
    array[i] = s.charAt(i);
}
for(int i = 0; i < s.length(); i++){
    System.out.print(array[i]);
}
String string = "123abc";
String[] array = string.split("");
System.out.println(Arrays.toString(array));
String string = "123abc";
String[] array; 
Pattern pattern = Pattern.compile("");
array = pattern.split(string);
System.out.println(Arrays.toString(array));

6. The array becomes a string

String[] string = {"123", "abc", "Strong"};
StringBuffer stringBuffer = new StringBuffer();
for(int i = 0; i < string.length; i++){
	stringBuffer.append(string[i]);
}
String string2 = stringBuffer.toString();
char[] data = {'a','b','c','happiness','sheep','sheep','1','2','3'};   
String s = new String(data);
char[] array = {'a','b','c','happiness','sheep','sheep','1','2','3'};   
String str = String.valueOf(array);
System.out.println(str);

7. Common methods of string

  • Returns the character at the specified index
String s = "https://blog.csdn.net/weixin_52605156";
char result = s.charAt(6);
System.out.println(result);
  • Compare this string with another object.
String a = "a";
String b = "b";
System.out.println(a.compareTo(b));
//Output - 1
String a = "abc";
String b = "bcde";
System.out.println(a.compareTo(b));
//If the initial letters of two strings are different, the ASCII difference of the initial letter is returned. If the initial letters are the same, the next character is compared until there are different letters. 
//Output - 1
String a = "abc";
String b = "abcd";
System.out.println(a.compareTo(b));
//In the above case, the length difference between the two strings is returned.
//Output - 1
  • Compares two strings in dictionary order, regardless of case.
String str1="php";
String str2="java";
System.out.println(str1.compareToIgnoreCase(str2));
//Returns the ASCII value of the first different character
//Output 6
String str1="java";
String str2="JAVAweb";
System.out.println(str1.compareToIgnoreCase(str2));
//Returns the number of characters with a difference
//Output - 3
  • Concatenates the specified string to the end of this string.
String s = "hello ";
s = s.concat("world!");
System.out.println(s);
//Output hello world!
  • Returns the character sequence in the specified array
char[] Str1 = {'1', '2', '3', '4', '5', '6', '7', '8', '9'};
String Str2 = "";
Str2 = Str2.copyValueOf(Str1);
System.out.println("Output:" + Str2);
Str2 = Str2.copyValueOf( Str1, 1 , 2);
System.out.println("Output:" + Str2);
//Output: 123456789
//Output: 23
  • Determines whether the string ends with the specified suffix
String string = new String("hello world!");
boolean a;
a = string.endsWith("hello");
System.out.println("True or false:" + a);
a = string.endsWith("world!");
System.out.println("True or false:" + a);
//True or false: false
//True or false: true
  • The string is compared to the specified object
String string1 = new String("abc");
String string2 = string1;//string1 and string2 share a space
String string3 = new String("abc");//string3 alone opens up another space
boolean a;
a = string1.equals(string2);
System.out.println("True or false:" + a);//True or false: true
a = string1.equals(string3);
System.out.println("True or false:" + a);//True or false: true
// ==Compare whether the reference addresses are the same, and equals() compare whether the string contents are the same.
  • Copy characters from string to target character array
public void getChars(int begin, int end, char[] array, int d)
//begin: the index of the first character in the string to copy.
//end: the index after the last character in the string to be copied.
//Array: target array.
//d: The starting offset in the destination array.
String string1 = new String("123abc Hello world! hello world!");
char[] array = new char[6];
string1.getChars(4, 10, array, 0);
System.out.print("Copied string:");
System.out.println(array);
//Copied string: bc Hello World
  • Detects whether two strings are equal in a region
public boolean regionMatches(boolean a,int b, String c,int d,int length)
/*
a : If true, the case will be ignored when comparing characters. If not, the default is false.
b : The starting offset in the string.
c : String parameter.
d : The starting offset of the sub region of the string parameter.
length : The number of characters to compare.
*/
String string1 = new String("www.csdn.com");
String string2 = new String("CSDN");
String string3 = new String("csdn");
System.out.print("Return value :" );//Return value: false
System.out.println(string1.regionMatches(4, string2, 0, 3));
System.out.print("Return value :" );//Return value: true
System.out.println(string1.regionMatches(4, string3, 0, 3));
System.out.print("Return value :" );//Return value: true
System.out.println(string1.regionMatches(true, 4, string2, 0, 3));
  • Detects whether the string starts with the specified prefix
String string = new String("www.csdn.com");
System.out.print("Return value: " );
System.out.println(string.startsWith("www"));
//Return value: true
  • Convert string to lowercase
String string = new String("ABCDEFG");
System.out.print("lower case : ");
System.out.println(string.toLowerCase());
//Change to lowercase: abcdefg
  • Converts string lowercase characters to uppercase
String string = new String("abcdefg");
System.out.print("Change to uppercase:" );
System.out.println(string.toUpperCase());
//Change to uppercase: ABCDEFG
  • Removes the leading and trailing whitespace of a string
String string = new String("  a b c d e f g  ");
System.out.print("The initial string is: ");
System.out.println(string);
System.out.print("Delete leading and trailing blanks: ");
System.out.println(string.trim());
/*
The initial string is: a b c d e f g  
Delete leading and trailing blanks: a b c d e f g
*/
  • Determines whether the string contains the specified character or string
String string = "csdn";
System.out.println(string.contains("c")); //true
System.out.println(string.contains("sd")); //true
System.out.println(string.contains("a")); //false
  • Determine whether the string is empty
String string = "csdn";  
String string2 = "";   
String string3 = "  ";   
System.out.println("string Empty:" + string.isEmpty());//Whether the string is empty: false
System.out.println("string2 Empty:" + string2.isEmpty());//Whether string2 is empty: true
System.out.println("string3 Empty:" + string3.isEmpty());//Whether string3 is empty: false

8. Common array methods

Array base, please move to: https://blog.csdn.net/weixin_52605156/article/details/120355549

  • Traversing a two-dimensional array
int array[][] = {{4,3},{5,3}};
int i = 0;
for(int a[]: array){
	i++;
    int j=0;
    for(int b: a){
		j++;
    	if(i==array.length && j==a.length){
    		System.out.println(b);
        	}else{
             	System.out.println(b + ",");
              }
          }
      }
  • Replace element
fill(int[] array,int value);
Use specified int Value assigned to int Type array
fill(int[] array,int fromIndex,int toIndex,int value);
fromIndex Is the index (included) of the first element to be populated with the specified value
toIndex Is the index (not included) of the last element populated with the specified value
value Is the value stored in all elements of the array
//We should be careful not to make the index position out of bounds, otherwise the array out of bounds exception will occur
  • Array sorting
Arrays.sort(object);//object is the name of the array
//The principle of sorting String type arrays in JAVA is that numbers are in front of letters and uppercase letters are in front of lowercase letters.
  • Array copy
copyOf(array,int newlength);
array Is the array to copy
newlength Is the length of the copied new array. If it is larger than the original, the spare space is filled with 0. If it is smaller, it is intercepted until the conditions are met.
copyOfRange(array,int fromIndex,int toIndex)
array Is the array object to copy
fromIndex Start copying the index position of the array, including
toIndex It refers to the last index position of the range to be copied, but it does not include Index Element of
  • Element query
binarySearch(Object[ ] array,Object key)
//Array is the array to search
//Key is the value to search. If the key is included in the array, the search value index will be returned; otherwise, - 1 or "-" will be returned
 binarySearch(Object[ ] array,int fromIndex, int toIndex ,Object key)
 array Array to retrieve
 fromIndex Is the index at the beginning of the specified range
 toIndex Is the index at the end of the range
 key Is the element to search
 //Using this method, you still have to sort the array
  • Array create ArrayList
String[] stringArray = { "a", "b", "c", "d", "e" };
ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(stringArray));
System.out.println(arrayList);
// [a, b, c, d, e]
  • Determine whether the array contains a value
String[] stringArray = { "a", "b", "c", "d", "e" };
boolean b = Arrays.asList(stringArray).contains("a");
System.out.println(b);
// true
  • Join two arrays
int[] intArray = { 1, 2, 3, 4, 5 };
int[] intArray2 = { 6, 7, 8, 9, 10 };
int[] combinedIntArray = ArrayUtils.addAll(intArray, intArray2);
String a[] = { "a", "b", "c" };
String b[] = { "d", "e", "f" };
List list = new ArrayList(Arrays.asList(a));
list.addAll(Arrays.asList(b));
Object[] c = list.toArray();
System.out.println(Arrays.toString(c));
  • Concatenate array elements according to the separator (remove the last separator)
String j = StringUtils.join(new String[] { "a", "b", "c" }, ", ");
System.out.println(j);
// a, b, c
  • ArrayList to array
String[] stringArray = { "a", "b", "c", "d", "e" };
ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(stringArray));
String[] stringArr = new String[arrayList.size()];
arrayList.toArray(stringArr);
for (String s : stringArr)
    System.out.println(s);
  • Invert array
int[] intArray = { 1, 2, 3, 4, 5 };
ArrayUtils.reverse(intArray);
System.out.println(Arrays.toString(intArray));
//[5, 4, 3, 2, 1]
  • Delete array elements
int[] intArray = { 1, 2, 3, 4, 5 };
int[] removed = ArrayUtils.removeElement(intArray, 3);//create a new array
System.out.println(Arrays.toString(removed));
  • Get array length
int  [ ] [ ] array = { {1 ,2,3},{4,5,6},{7,8,9}};
int rows = array.length;
int columns = array[0].length; 
  • Array gets the maximum and minimum values
Integer[] numbers = { 8, 2, 7, 1, 4, 9, 5};
int min = (int) Collections.min(Arrays.asList(numbers));
int max = (int) Collections.max(Arrays.asList(numbers));
System.out.println("minimum value: " + min);
System.out.println("Maximum: " + max);
  • Determine whether the arrays are equal
int[] array = {1,2,3};
int[] array1 = {1,2,3,4};
int[] array2 = {1,2,3};
System.out.println("array And array1 Are they equal? "+Arrays.equals(array, array1));
System.out.println("array And array2 Are they equal? "+Arrays.equals(array, array2));

reference material: https://www.apiref.com/java11-zh/java.base/java/util/package-summary.html
https://www.runoob.com/java/java-tutorial.html

Topics: Java string api array