Gibt es substr_count in CBuilder?



  • Hallo.

    [b]substr_count[/b]
    
    [i](PHP 4, PHP 5)[/i]
    substr_count --  Ermittelt, wie oft eine Zeichenkette in einem String vorkommt
    Beschreibung
    int substr_count ( string haystack, string needle [, int offset [, int length]] )
    
    Die Funktion substr_count() ermittelt, wie oft needle in dem String haystack vorkommt, und gibt die Anzahl der Vorkommen zurück. Beachten Sie, dass der Parameter needle case sensitive ist.
    

    Beispie: $anzahl = substr_count("hello world!","el");

    Gibt es eine solche Funktion in CBuilder?
    Ich habe keine gefunden und angefangen mir selber was zu basteln, komme aber nicht weiter

    //---------------------------------------------------------------------------
    int substr_count(AnsiString Text, AnsiString Sub);
    {
        int anzahl = 0;
        for (int i=0;i<Text.Lenght();i++)
        {
    //.........
        }
        return anzahl;
    }
    //---------------------------------------------------------------------------
    

    Kann mir da jemand helfen?



  • Es gibt die Funktion

    int __fastcall Pos(const AnsiString& subStr) const;
    

    Sowas wäre eine Möglichkeit:

    AnsiString test="Hello world, hello sunshine, hello was weiß ich";
    AnsiString such_string="el";
    int anzahl=0;
    AnsiString proc=test;
    
    while(proc.Pos(such_string)!=0)
    { 
     proc=proc.Delete(proc.Pos(such_string),such_string.Length()); 
     anzahl++;
    }
    
    Edit1->Text=IntToStr(anzahl);
    


  • Cool! Danke 😉

    Falls noch Andere, andere Variante haben, würde ich die gerne auch sehen 😃



  • Mit Standard-Strings geht es etwas kürzer und ohne Löschen

    std::string text = "Hello world, hello sunshine, hello was weiss ich";
    std::string such = "el";
    int pos = -1;
    size_t anzahl(0);
    while( (pos = text.find(such, pos+1)) != string::npos) ++anzahl;
    Edit1->Text = IntToStr(anzahl);
    

Anmelden zum Antworten