查找子字符串中每个字符的索引

时间:2014-10-06 18:08:05

标签: java string indexing substring

我觉得我的逻辑在这里很合适;我不觉得自己完全迷失了。但是,我确实知道我到底做错了什么。我总能找到子字符串开头的索引,但我永远找不到用户输入的任何单词索引的完整计数(例如3,4,5,6)。

我一直在努力解决这个问题大约一个星期试图弄清楚如何自己做,我无法做对。

import java.util.Scanner;
public class midterm
{
    public static void main (String[] args)

    {
        Scanner keyboard = new Scanner(System.in);

        String simplePhrase;
        String portionPhrase;
        int portionIndex;
        int portionCount;
        int portionIndexTotal;

        System.out.println("Enter a simple phrase:");
        simplePhrase = keyboard.nextLine();

        int phraseLength = simplePhrase.length();
        System.out.println("Phrase length:" +phraseLength);

        System.out.println("Enter a portion of previous phrase:");
        portionPhrase = keyboard.nextLine();

        String portionPhraseSub = simplePhrase.substring(portionPhrase);

        portionIndex = simplePhrase.indexOf(portionPhraseSub);

        for (portionIndex; portionIndex <= portionPhrase; portionIndex++)
        {
            System.out.println("Portion phrase index:"+portionIndex);
        }
     }  
}

1 个答案:

答案 0 :(得分:0)

我仍然对你想要的东西感到困惑。只需要知道两件简单的事情,你似乎要把它变得比它需要的更复杂。

获取单个字符的索引,例如&#34; c&#34;在&#34; acorn&#34;这个词中,你会这样做:

String s = "acorn";
int cIndex = s.indexOf("c");
System.out.println("The index of c is: " + cIndex);

如果要查看字符串是否包含块,请使用完全相同的方法。因此,如果我们正在查看&#34; acorn&#34;再次,你想看到&#34; orn&#34;碰巧,你这样做:

String s = "acorn";
int ornIndex = s.indexOf("orn");
System.out.println("The index of orn is: " + ornIndex);

请记住,索引在java中从0开始,因此索引为&#34; a&#34; in&#34; acorn&#34;是&#34; c&#34;是&#34; o&#34;是2,依此类推。

我希望有所帮助。祝你好运:)

编辑:您刚评论过: &#34;我想,我的问题是我的代码要编译,我如何计算我的子字符串的每一个字母?&#34;

我尽可能地回答,尽管如此,这仍然是一个令人困惑的问题。

你甚至算什么算?&#34;每一封信?如果你想把你的单词分成单个字母,你可以这样做:

String s = "acorn";
char[] characters = new char[s.length()-1];
for(int i = 0; i < s.length() - 1; i++) {
    char[i] = s.charAt(i);
}

但是我不知道你为什么要这样做...你总是可以使用STRING.charAt(index)访问给定索引处的字符串中的任何字符,或者如果你想拥有一个字符串结果,STRING.substring(索引,索引+ 1)

相关问题