то, что самый чистый путь состоит в том, чтобы удалить все дополнительные пространства из запятой ввода данных пользователем, разграничило строку в массив

std::streambuf * buf;
std::ofstream of;

if(!condition) {
    of.open("file.txt");
    buf = of.rdbuf();
} else {
    buf = std::cout.rdbuf();
}

std::ostream out(buf);

, Который связывает базовый streambuf или суда или потока выходного файла к. После этого можно записать в, и это закончится в правильном месте назначения. Если Вы просто хотите это, все идущее в std::cout входит в файл, можно также сделать

std::ofstream file("file.txt");
std::streambuf * old = std::cout.rdbuf(file.rdbuf());
// do here output to std::cout
std::cout.rdbuf(old); // restore

, Этот второй метод имеет недостаток, что это не безопасное исключение. Вы возможно хотите записать класс, который делает это использование RAII:

struct opiped {
    opiped(std::streambuf * buf, std::ostream & os)
    :os(os), old_buf(os.rdbuf(buf)) { }
    ~opiped() { os.rdbuf(old_buf); }

    std::ostream& os;
    std::streambuf * old_buf;
};

int main() {
    // or: std::filebuf of; 
    //     of.open("file.txt", std::ios_base::out);
    std::ofstream of("file.txt");
    {
        // or: opiped raii(&of, std::cout);
        opiped raii(of.rdbuf(), std::cout);
        std::cout << "going into file" << std::endl;
    }
    std::cout << "going on screen" << std::endl;
}

Теперь, что бы ни случилось, станд.:: суд находится в чистом состоянии.

10
задан Gordon Gustafson 27 September 2009 в 16:12
поделиться

7 ответов

You can use Regex.Split for this:

string[] tokens = Regex.Split("basketball, baseball, soccer ,tennis", @"\s*,\s*");

The regex \s*,\s* can be read as: "match zero or more white space characters, followed by a comma followed by zero or more white space characters".

18
ответ дан 3 December 2019 в 14:34
поделиться
string[] values = delimitedString.Split(',').Select(s => s.Trim()).ToArray();
8
ответ дан 3 December 2019 в 14:34
поделиться
string s = "ping pong, table tennis, water polo";
string[] myArray = s.Split(',');
for (int i = 0; i < myArray.Length; i++)
    myArray[i] = myArray[i].Trim();

That will preserve the spaces in the entries.

3
ответ дан 3 December 2019 в 14:34
поделиться

Split the items on the comma:

string[] splitInput = yourInput.Split(',', StringSplitOption.RemoveEmptyEntries);

and then use

foreach (string yourString in splitInput)
{
    yourString.Trim();
}
1
ответ дан 3 December 2019 в 14:34
поделиться

You can split on either comma or space, and remove the empty entries (those between a comma and a space):

string[] values = delimitedString.Split(new char[]{',',' '}, StringSplitOption.RemoveEmptyEntries);

Edit:
However, as that doesn't work with values that contain spaces, instead you can split on the possible variations if your values can contain spaces:

string[] values = delimitedString.Split(new string[]{" , ", " ,", ", ", ","}, StringSplitOptions.None);
3
ответ дан 3 December 2019 в 14:34
поделиться

String.Replace(" ","") before you split the string

0
ответ дан 3 December 2019 в 14:34
поделиться

I would firstly split a text by ",", and then use Trim method to remove spaces on start and end of the each string. This will add support for string with spaces to your code.

0
ответ дан 3 December 2019 в 14:34
поделиться
Другие вопросы по тегам:

Похожие вопросы: