[英]Convert string to int using char array
how can I create a loop that also turns string "abcc" into the sum of their letter position, say a=1 b=2 c=3 and it sums the string 1+2+3+3=9. 我如何创建一个循环,该循环还将字符串“ abcc”转换为其字母位置的总和,例如a = 1 b = 2 c = 3并将字符串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);
}
}
You can make use of the fact that characters can be cast to an Integer, and thereby take on their ASCII value. 您可以利用以下事实:可以将字符转换为整数,从而采用其ASCII值。 eg System.out.println((int)'a') would print '97'. 例如System.out.println((int)'a')将输出'97'。 Knowing that, you only have to subtract a certain number based on whether it's an upper- or lowercase letter and you get 1 for a, 2 for b etc. 知道这一点,您只需要根据它是大写还是小写字母减去某个数字,就可以得到a等于1,b等于2等。
Here are two solutions: One with a loop as requested, and one with recursion. 这里有两种解决方案:一种具有请求的循环,一种具有递归。 This works with both upper- and lowercase letters, but doesn't take non-alphabetical letters into account. 这适用于大写和小写字母,但不考虑非字母的字母。 This can easily be tested for in an if-statement, with the following criteria: Character.isAlphabetic( c )
. 可以使用以下条件轻松地在if语句中对此进行测试: 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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.