【问题标题】:Print the positions of a character, including the positions of space between them, in a string在字符串中打印字符的位置,包括它们之间的空格位置
【发布时间】: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:
  • 因为两个答案都用下一行替换下一个,它可以工作

标签: java string


【解决方案1】:

使用读取整行scanner.nextLine(),而不是只读取第一个单词的scanner.next()。打印str 的值并查看它包含的内容:)

接下来,您只需要一台扫描仪。删除Scanner sc2=new Scanner(System.in);使用 sc1 代替 sc2

【讨论】:

    【解决方案2】:

    只替换 String str=sc1.next();通过字符串 str=sc1.nextLine();这会奏效。 请尝试一下。

    【讨论】:

      猜你喜欢
      • 2016-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-16
      • 1970-01-01
      • 2015-02-04
      相关资源
      最近更新 更多