如何在字符串中查找特定字符串的出现位置

时间:2016-06-09 15:18:12

标签: java string

问题在于,我试图找到并只获得一次字符串,当我能得到一个字符串的唯一方法是使用多次出现的关键字。

  

实施例。 4个土豆, 4(我想要的字符串),4个房子,4个车

当我无法键入字符串可能包含的任何关键字时,我如何只获取我想要的字符串。

想象一下,它试图从文章中只拿出一个段落。

我已经尝试过stringy.replaceAll(Str1,Str2);变数,但无济于事。所有这一切都是我替换所有的字符串(使用名称替换所有字符串)

package com.donovan.cunningham;

import java.util.ArrayList;
import java.util.Random;

public class EssayCreator {
//Creating varz
    private static String[] lf = {"happy", "sad", "unhappy", "atractive",
        "fast", "lazy"};
    private static String[] op = {"estatic", "melhencohly", "depressed", 
        "alluring", "swift", "lackadaisical"};
    private static String pF = "   ";
    private static String temp[];
    private static String conv = "   ";
    private static String comm = ", ";
    private static Random random = new Random();
    private ArrayList<String> array = new ArrayList<String>();

    public static void Converter(String in) {
        in = in.replace(comm, conv);
        for (int i = 0; i < lf.length; i++){    
            in = in.replace(lf[i], op[i]);
        }
        in = in.replace(conv, comm);
        //int rand = random.nextInt(in.indexOf(pF));
        for (int i = 0; i < in.indexOf(pF); i++){
            /*
                Where I want to get an exact string of an essay
                I'd convert pF to conv, and then remove the paragraph to 
                change the order
            } */
        }

        CreateGUI.output.setText(in);
        Sound.stopSound();
    }
}

由于

2 个答案:

答案 0 :(得分:0)

你的问题不是很清楚。您希望(1)找到您不知道或想要的最多出现字符串(2)替换您知道的出现字符串吗?

最天真的做法(1)是按空格切割文本并将它们放在字符串到整数的HashMap中以计算出现次数最多的字符串。您还可以扫描此HashMap以查找所有N-occurence字符串

对于(2),假设您已经知道要查找哪个键字符串,可以递归地在String中应用indexOf(String str,int fromIndex),如下所示:

int occurenceCount = 0;
String input = "Here is your text with key_word1, key_word2, ...etc"; 
StringBuffer output = new StringBuffer();
int index = input.indexOf("key_word");
int copiedIndex = 0;

for(index>0)
{
  output.append(input.substring(copiedIndex, index));
  occurenceCount++;
  if(occurenceCount==4) //Find 4th occurrence and replaced it with "new_key_word"
  {
    output.append("new_key_word")
  }
  else
  {
    output.append("key_word")
  }
  copiedIndex = index+("key_word".length);
  index = input.indexOf("key_word", index+("key_word".length));
  if(index==-1)
    break;
}

参考:https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(java.lang.String,%20int)

不确定我是否已经回答了你的问题......

答案 1 :(得分:0)

我已经梳理了你的代码并尝试使用我用你提供的神秘信息制作的用例来运行它。正如上面的人所说,目前尚不清楚你想要完成什么。如果String的内置方法不够,通常regex是您尝试进行更复杂的字符串模式匹配时的朋友。尝试谷歌搜索段落regex java'中的'模式匹配字符串'或类似的东西。同时,我在您的代码中添加了一些注释,这可能有助于使这个问题更加清晰。如果我能更好地了解你想要做什么,我很乐意提供帮助。请参阅以下代码和评论:

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class EssayCreator {
    // Creating varz
    private static String[] lf = { "happy", "sad", "unhappy", "atractive",
        "fast", "lazy" };
    private static String[] op = { "estatic", "melhencohly", "depressed",
        "alluring", "swift", "lackadaisical" };
    private static String pF = "   ";
    private static String temp[];
    private static String conv = "   ";
    private static String comm = ", ";
    private static Random random = new Random();
    private List<String> array = new ArrayList<String>();

    // Bradley D: Just some side notes here: 
    // Don't capitalize method names and don't use nouns.
    // They're not class names or constructors. Changed Converter to convert. It'd also be good to
    // stipulate what you are converting, i.e. convertMyString to make this a
    // little more intuitive
    public static void convert(String in) {
        /*
         * Bradley D: First, you are replacing all commas following by a space
         * with 3 spaces. Be good to know why you doin that?
         */
        in = in.replace(comm, conv);
        for (int i = 0; i < lf.length; i++) {
            in = in.replace(lf[i], op[i]);
        }
        /*
         * Bradley D: Now you are replacing the 3 spaces with a comma and a
         * space again??
         */
        in = in.replace(conv, comm);

        // Bradley D: Not really sure what you are trying to iterate through
        // here. in.indexOf(pF) is -1
        // for the use case I've created for you with the text below (what did I
        // miss?)...
        // Perhaps you're trying to find the first place in your essay where pF
        // (3 spaces) occurs....
        // but you've already reconverted your 3 spaces back to a comma and
        // single space, so I'm getting even more lost here....
        // int rand = random.nextInt(in.indexOf(pF));
        for (int i = 0; i < in.indexOf(pF); i++) {
            /*
             * Bradley D: What is pF?? It appears to be the same as comm...
             */
            /*
             * Where I want to get an exact string of an essay I'd convert pF to
             * conv, and then remove the paragraph to change the order }
             */

            // Bradley D: Ok, so if you can make this question clear, I'll give it a shot here
        }
        // Bradley D: Commenting this out since it was not included
        // CreateGUI.output.setText(in);
        // Sound.stopSound();
    }

    public static void main(String[] args) {
        EssayCreator ec = new EssayCreator();
        String essay = "Let's see if we find the desired string in here.  "
            + "Are we happy? Nope, we're not happy.  Who's happy? What does happiness mean anyway? "
            + "I'd be very happy if this question we're more clear, but let's give it a go anyway. Maybe "
            + "we're lazy, and that's not attractive, thus rendering us unhappy and lackadasical... jk! "
            + "So hey man... why are you replacing all of the commas with spaces?  "
            + "Can you put comments in your code? What is pF? "
            + "Also you should not capitalize method names.  They should be in camelCase and they should not "
            + "be nouns like Converter, which makes them look like a constructor.  Methods represent "
            + "an action taken, so a verb to describe them is standard practice. "
            + "So use convert, but what are you converting? convertString?? convertWords? "
            + "Anyway, making your method names intuitive would be helpful to anyone trying to understand "
            + "the code.";
        ec.convert(essay);
    }
}