Convert string to int using char array

how can I create a loop that also turns the string "abcc" into the sum of their letter position, say a = 1 b = 2 c = 3 and sums the string 1 + 2 + 3 + 3 = 9.

import java.util.Arrays; public class Test { public static void main(String[] args) { String original = "hello"; char[] chars = original.toCharArray(); Arrays.sort(chars); String sorted = new String(chars); System.out.println(sorted); } } 
+4
source share
4 answers

You can use ASCII values. a is 97 , b is 98 , etc.

 private int printSum(String original){ int sum = 0; if(original!=null){ char[] arr = original.toLowerCase().toCharArray(); for(int x :arr){ sum+= (x-96); } } return sum; } 
+6
source

You can use the fact that characters can be passed to Integer and thus accept their ASCII value. for example, System.out.println ((int) 'a') will print '97'. Knowing this, you only need to subtract a specific number based on whether it is an upper or lower case letter, and you get 1 for a, 2 for b, etc.

+3
source
  • Remove characters from alphabet from string using regular expressions
  • Change string using toLower () or toUpper ()
  • Convert string to charArray
  • Set the initial result to 0
  • Foreach char in the array, subtract the char value from 64 (if you use UPPERCASE) or 96 (if you use lower case) and add it to the result
+1
source

Here are two solutions: one with a loop on demand and one with recursion. This works with both uppercase and lowercase letters, but does not account for non-alphabetic letters. This can be easily verified in an if-statement with the following criteria: Character.isAlphabetic( c ) .

 public class Main { static final int LOWERCASE_OFFSET = 96; static final int UPPERCASE_OFFSET = 64; public static void main( String[] args ){ System.out.println(recursion( "Abcc" )); } static int recursion( String str ) { if( str.isEmpty() ) return 0; char c = str.charAt( 0 ); int charVal = Character.isUpperCase( c ) ? c - UPPERCASE_OFFSET : c - LOWERCASE_OFFSET; return charVal + recursion( str.substring( 1 ) ); } static int loop( String str ) { int val = 0; for( char c : str.toCharArray() ) { val += Character.isUpperCase( c ) ? c - UPPERCASE_OFFSET : c - LOWERCASE_OFFSET; } return val; } } 
+1
source

Source: https://habr.com/ru/post/1482733/


All Articles