2016-06-09 14 views
-1

Das Problem ist, ich versuche nur ein Vorkommen einer Zeichenfolge zu finden und zu erhalten, wenn die einzige Möglichkeit, die ich bekomme, ist mit einem Schlüsselwort das tritt mehrmals auf.So finden Sie eine bestimmte Vorkommen einer Zeichenfolge innerhalb einer Zeichenfolge

Ex. 4 Kartoffeln, 4 (string ich will), 4 Haus, 4 Auto

Wie ich nur die Zeichenfolge bekommen was ich will, wenn ich keine Schlüsselwörter eingeben können, die die Zeichenfolge enthalten könnte.

Stellen Sie sich vor, Sie versuchen nur einen Absatz aus einem Aufsatz zu nehmen.

Ich habe versucht, die stringy.replaceAll (Str1, Str2); variabel, aber ohne Erfolg. Alles, was ist, ich (mit einem Namen gehen Figur wie alle ersetzen) ersetzen alle die Zeichenfolge geschieht

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(); 
    } 
} 

Dank

+1

Ich bin sehr verwirrt durch Ihre Frage. Würde es Ihnen etwas ausmachen, durch ein Beispiel zu gehen, was Sie tun möchten? Es klingt, als ob Sie nach regulären Ausdrücken suchen. Sie können nach Mustern in einer Zeichenfolge suchen. Sie können in die Matcher-Klasse für Java schauen. Ich glaube, es gibt eine Methode namens replaceFirst, die Sie auf den richtigen Weg bringen könnte – pythonHelpRequired

+0

Finden Sie die zweite "4" mit String indexOf. Finde die dritte "4". Ihr Teilstring befindet sich zwischen der ersten Position (der zweiten "4") und der dritten Position. Als Alternative wird String auf das Komma + Leerzeichen aufgeteilt, und Sie erhalten dann den Teilstring vom zweiten Teil. –

+0

Was ist Ihre Abfrage genau, können Sie klarer sein? – jcool

Antwort

0

Ihre Frage aber ist nicht ganz klar. Sie wollen (1) die Zeichenfolge mit dem meisten Vorkommen finden, die Sie nicht kennen oder die Sie (2) als Vorkommenszeichenfolge verwenden möchten, die Sie kennen?

Die naivste Art zu tun (1) ist, Ihren Text nach Leerzeichen zu zerlegen und sie in eine String-to-Integer-HashMap zu setzen, um die am häufigsten auftretende Zeichenfolge zu berechnen. Sie können diese HashMap auch scannen, um alle N-Vorkommenstrings zu finden

Für (2) vorausgesetzt, dass Sie bereits wissen, welche Schlüsselzeichenfolge Sie suchen möchten, können Sie indexOf (String str, int fromIndex) in String rekursiv anwenden wie folgt:

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; 
} 

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

nicht sicher, ob ich Ihre Frage aber beantwortet hatte ...

+0

Hat nicht wirklich geholfen, aber danke fürs ausprobieren –

0

ich habe durch den Code gekämmt und versuchte es mit einem Anwendungsfall läuft ich gemacht aus den kryptischen Informationen, die du gegeben hast. Wie die Leute oben sagen, ist es nicht klar, was Sie erreichen wollen. Normalerweise ist Regex Ihr Freund, wenn Sie versuchen, einen komplexeren String-Mustervergleich durchzuführen, wenn die eingebauten Methoden von String nicht ausreichen. Versuchen Sie, 'pattern match string' im Absatz regex java 'googlen oder etwas zu diesem Zweck. Inzwischen habe ich Ihrem Code einige Kommentare hinzugefügt, die dazu beitragen könnten, diese Frage klarer zu machen. Gerne helfen, wenn ich besser verstehe, was Sie tun möchten. Siehe Code und Kommentare unten:

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); 
    } 
} 
Verwandte Themen