用户将输入一个字符串,程序应该识别整数。
如果用户输入Hello12 3
,则应输出:
The integral numbers are:
id1 12
id2 3
但在我的代码中,它输出
The integral numbers are:
int1
int2
int3
int4
int5
int6 12
int7 3
我该如何解决? 我的代码:
import java.util.*;
public class LexicalAnalyzer {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
String str;
int j=0;
System.out.println("Lexical Analyzer for Algebraic Expressions\n");
System.out.print("Enter the String: ");
str = input.nextLine();
System.out.println("String length is: "+str.length());
System.out.println("\nThe integral numbers are: \n");
String intNum = str.replaceAll("[^0-9]", " ");
String[] intSplit = intNum.split(" ");
for(int i=0;i<intSplit.length;i++){
System.out.println("int"+(i+1)+" "+intSplit[i]);
}
}
}
答案 0 :(得分:1)
您正在用空格替换每个非数字字符。您需要将其替换为while ( true )
{
cout << "Enter a positive integer N (<1 to stop): ";
unsigned int n;
cin >> n;
if ( !( cin >> n ) || n == 0 ) break;
sum = 0;
for (unsigned int count = 1; count <= n; count++)
sum = sum + (1.0/count);
if ( n > 0 ) cout << "Sum = " << sum << endl;
}
cout << "Bye! ";
,以便没有多余的空格。然后你拆分空间,你会得到所需的结果。此外,您需要使用""
来保留数字之间的空格,以便空格不会被[^0-9\\s]
(空字符串)替换。
替换:
""
with:
String intNum = str.replaceAll("[^0-9]", " ");
答案 1 :(得分:0)
不要在修改字符串时浪费时间(CPU资源),而只是搜索你想要的东西:
Matcher m = Pattern.compile("[0-9]+").matcher(str);
for (int i = 1; m.find(); i++)
System.out.println("int" + i + " " + m.group());