3 回答

TA貢獻1963條經(jīng)驗 獲得超6個贊
您可以使用Character.isDigit(char)區(qū)分數(shù)字和非數(shù)字字符,因為實際上這是在同一行中對多個字符進行分組的單一標準。
它會給:
public static void main(String[] args) {
String inputString = "1+3,432.123*4535-24.4";
String currentSequence = "";
for (int i = 0; i < inputString.length(); i++) {
char currentChar = inputString.charAt(i);
if (Character.isDigit(currentChar)) {
currentSequence += currentChar;
continue;
}
System.out.println(currentSequence);
System.out.println(currentChar);
currentSequence = "";
}
// print the current sequence that is a number if not printed yet
if (!currentSequence.equals("")) {
System.out.println(currentSequence);
}
}
Character.isDigit()依賴于 unicode 類別。
您可以自己編寫代碼,例如:
if (Character.getType(currentChar) == Character.DECIMAL_DIGIT_NUMBER) {...}
或者,您可以通過檢查 的int值char是否包含在數(shù)字的ASCII十進制值范圍內,在較低級別對其進行編碼:
if(currentChar >= 48 && currentChar <= 57 ) {
它輸出你想要的:
1
+
3
,
432
.
123
*
4535
——
24
.
4

TA貢獻1833條經(jīng)驗 獲得超4個贊
這比你想象的要容易。
首先:要獲取包含字符串字符的數(shù)組,您只需使用toCharArray()所有字符串都具有的方法。
前任。myString.toCharArray()
第二:當你看到一個字符不是數(shù)字時,你想移動到下一行,打印字符,然后再次移動到下一行。
以下代碼正是這樣做的:
public class JavaApplication255 {
public static void main(String[] args) {
String inputString = "1+3,432.123*4535-24.4";
char[] destArray = inputString.toCharArray();
for (int i = 0 ; i < destArray.length ; i++){
char c = destArray[i];
if (isBreakCharacter(c)){
System.out.println("\n" + c);
} else {
System.out.print(c);
}
}
}
public static boolean isBreakCharacter(char c){
return c == '+' || c == '*' || c == '-' || c == '.' || c == ',' ;
}

TA貢獻1847條經(jīng)驗 獲得超7個贊
這是一個可能的解決方案,我們逐個字符地添加到將成為我們的數(shù)字的現(xiàn)有字符串中,或者將字符串添加到數(shù)組中,清除當前數(shù)字,然后添加特殊字符。最后,我們遍歷數(shù)組的次數(shù)與找到數(shù)字或非數(shù)字字符的次數(shù)相同。我使用 ASCII 表將字符識別為數(shù)字,該表將在您的整個編程生涯中派上用場。最后,我將數(shù)組更改為字符串數(shù)組,因為字符不能包含“432”之類的數(shù)字,只能包含“4”或“3”或“2”。
String inputString = "1+3,432.123*4535-24.4";
int stringLength = inputString.length();
String[] destArray = new String[stringLength];
int destArrayCount = 0;
String currentString = "";
for (int i=0; i<stringLength; i++)
{
//check it's ascii value if its between 0 (48) and 9 (57)
if(inputString.charAt(i) >= 48 && inputString.charAt(i) <= 57 )
{
currentString += inputString.charAt(i);
}
else
{
destArray[destArrayCount++] = currentString;
currentString = "";
//we know we don't have a number at i so its a non-number character, add it
destArray[destArrayCount++] = "" + inputString.charAt(i);
}
}
//add the last remaining number
destArray[destArrayCount++] = currentString;
for(int i = 0; i < destArrayCount; i++)
{
System.out.println("(" + i + "): " + destArray[i]);
}
重要- 如果使用某種類型的字符串,此算法將失敗。你能找到這個算法失敗的字符串嗎?你能做些什么來確保計數(shù)總是正確的,而不是有時比實際計數(shù)大 1?
添加回答
舉報