How would I replace a part of a string that contains unknown values

-1

So i want to replace some a part of a text file knowing only that it looks like this:

Part "name" {11.015586 1.208383 -5.521754 0.001870 -0.975887 0.218267 0xffffffff 0.133086 0.811246 0.000000 1.000000}

name would be inputted from terminal and inside of brackets would have hundreds of lines of values as well as other brackets inside it. Also the word Part would have a tab before it, there would be a new line after the first { before last one there also would be a new line and a tab. How would I go about replacing the part inside the brackets or even all of it with another string.

c#
string
replace
asked on Stack Overflow Apr 3, 2021 by syncstar

1 Answer

0

A solution could be:

            string unknownPieceOfText = "Part \"name\" {11.015586 1.208383 -5.521754 0.001870 -0.975887 0.218267 0xffffffff 0.133086 0.811246 0.000000 1.000000}";
            string anotherString = "another string";

            int OpeningAccolade = unknownPieceOfText.IndexOf('{');
            int ClosingAccolade = unknownPieceOfText.IndexOf('}');

            string newString = unknownPieceOfText.Substring(0, OpeningAccolade + 1) + anotherString + unknownPieceOfText.Substring(ClosingAccolade);

            Console.WriteLine(newString);

It outputs: Part "name" {another string}

But we do not know if there are more '{' or '}' inside that text. Especially more '}' will make this solution worthless... 😉 (and it already has not much value)

answered on Stack Overflow Apr 3, 2021 by Luuk

User contributions licensed under CC BY-SA 3.0