Jesepy
Jesepy

Reputation: 37

Managing Strings In C++

So I make an array of string pointers and put a string in at position 0 of the array. If I don't know the length of the string in word[0] how do I find it? How do I then manage that string, because I want to remove the "_." and "." part of the string so I will be left with "apple Tree".How do I resize that string? (functions like strcpy,strlen, or string.end() didn't work, I get errors like "can't convert string to char*" etc)

#include <iostream>
#include <string.h>
#include <stdio.h>
#include <string>

using namespace std;

int main()
{
    int counter=0;
    string* word = new string[0];

    word[0] = "apple_.Tree.";

    return 0;
}

Edit:what i want to do is make a dynamic array of strings(not using vector) and then edit the strings inside

Upvotes: 0

Views: 175

Answers (1)

VLL
VLL

Reputation: 10155

string is a class, so you can use its member functions to manage it. See the documentation.

To remove characters, use std::erase (see this answer).

#include <iostream>
#include <string>
#include <algorithm>

int main() {
    // Create array of 10 strings
    std::string array[10];
    array[0] = "apple_.Tree.";

    std::cout << array[0].size() << "\n";

    array[0].erase(std::remove(array[0].begin(), array[0].end(), '.'), array[0].end());
    array[0].erase(std::remove(array[0].begin(), array[0].end(), '_'), array[0].end());

    std::cout << array[0];

    return 0;
}

Upvotes: 3

Related Questions