【发布时间】:2015-04-07 11:00:56
【问题描述】:
如何在不使用内置函数的情况下在字符串中打印字符的位置,包括它们之间的空格位置?
例如: 让字符串输入为“我爱我的印度”
字符输入 ='i'
输出必须是:'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++;
}
}
【问题讨论】:
-
请定义一个
built-in function函数集 -
@TheLostMind 是的,删除了那个 c:
-
因为两个答案都用下一行替换下一个,它可以工作