Need space after comma in text

We have some code where we have text in column that does not have a space after comma. So when we open the resulting DOCX in MS Word, it shows red squiggly line below(please see attached pacture). Is there any way we can trim such text so that we introduce a space between the a comma and the text following if there is no space?

cellToCloneFrom = new Cell(doc);

cellToCloneFrom.CellFormat.Width = cellWidth;
// Add a paragraph to the cell as well as a new run with some text.

cellToCloneFrom.AppendChild(para);
cellToCloneFrom.FirstParagraph.AppendChild(new Run(doc, "26 - Houston,TX"));

//Formatting
cellToCloneFrom.FirstParagraph.Runs[0].Font.Color = context.ContentCellFormat.FontColor;
cellToCloneFrom.FirstParagraph.Runs[0].Font.Name = context.ContentCellFormat.FontName;
cellToCloneFrom.FirstParagraph.Runs[0].Font.Size = context.ContentCellFormat.FontSize;

if (context.ContentCellFormat.BackgroundColor.HasValue)
    cellToCloneFrom.CellFormat.Shading.BackgroundPatternColor = context.ContentCellFormat.BackgroundColor.Value;

cellToCloneFrom.CellFormat.SetPaddings(context.ContentCellFormat.PaddingLeft, context.ContentCellFormat.PaddingTop, context.ContentCellFormat.PaddingRight, context.ContentCellFormat.PaddingBottom);
// Add the cell to the row.
row.AppendChild(cellToCloneFrom);

@leopius You can use regular expression to to put whitespace after comma. For example see the following simple code:

string value = "26 - Houston,TX";
value = Regex.Replace(value, "([a-zA-Z]+,)([a-zA-Z]+)", "$1 $2");

Also, if the values already are in the document and you cannot process input strings, you can use Range.Replace method:

Document doc = new Document(@"C:\Temp\in.docx");
FindReplaceOptions opt = new FindReplaceOptions();
opt.UseSubstitutions = true;
doc.Range.Replace(new Regex("([a-zA-Z]+,)([a-zA-Z]+)"), "$1 $2", opt);
doc.Save(@"C:\Temp\out.docx");

Thank you Alexey. Works

1 Like