如何在不使用内置函数的情况下在字符串中打印字符的位置(包括它们之间的空间位置)?
例如: 让字符串输入是"我爱我的印度"
字符输入='我'
输出必须是:' i'是:0 10 13
我试过这个:
String str="i love my india";
char c='i';
char ch[]=str.toCharArray();
int pos=0;
for(int i=0;i<str.length();i++)
{
if(ch[i]==c)
{
System.out.print(pos+" ");
}
pos++;
}
我得到了以上逻辑的输出,但是我尝试使用扫描类,输出错误:以下代码有什么问题?
public static void main(String[] args)
{
Scanner sc1=new Scanner(System.in);
System.out.println("enter the string:");
String str=sc1.next();
System.out.println("---------------------------");
Scanner sc2=new Scanner(System.in);
System.out.println("enter the character:");
char c=sc2.next().charAt(0);
char ch[]=str.toCharArray();
int pos=0;
for(int i=0;i<str.length();i++)
{
if(ch[i]==c)
{
System.out.print(pos+" ");
}
pos++;
}
}
答案 0 :(得分:0)
使用scanner.nextLine()
读取整行而不是只读取第一个单词的scanner.next()
。打印str
的值并查看它包含的内容:)
接下来,您只需要1个扫描仪。删除Scanner sc2=new Scanner(System.in)
;使用sc1而不是sc2
答案 1 :(得分:0)
只替换String str = sc1.next(); by String str = sc1.nextLine();这会奏效。 试试吧。