We're sorry Aspose doesn't work properply without JavaScript enabled.

# Selecting Text based on an index position and String Length

hi,

I want to select some text based on an index position in the document and length and delete it. I don’t know the string contents so I can’t use range.replace which depends on a regex expression.

How do I do this.

Thanks Bruce

Hi
Thanks for your request. There is no such built-in functionality. However, I think this could be implemented. If you need I can try to create sample code for you. If so please attach sample document and provide me test inputs (indexes and lengths).
Best regards.

hi,

Just any document would be fine. Say with 50 characters in it and the ability to delete characters 10-15.

Should be very simple.

Cheers Bruce

Hi
Thanks you for additional information. You can try using the following code:

int startPosition = 9;
int length = 5;
// Open document
Document doc = new Document(@"Test065\in.doc");
// Get paragraph which we should edit
Paragraph par = doc.FirstSection.Body.FirstParagraph;
int currentPosition = 0;
foreach (Run run in par.Runs)
{
// Set current position
currentPosition += run.Text.Length;
if (currentPosition <= startPosition)
{
continue;
}
else
{
int tmpStart = 0;
int tmpLenth = 0;
// Calculate position in current run
if (currentPosition - run.Text.Length < startPosition)
{
tmpStart = startPosition - (currentPosition - run.Text.Length);
}
// Calculate lenth of sub string that should be removed from current run
if (run.Text.Length - tmpStart >= length)
{
tmpLenth = length;
}
else
{
tmpLenth = run.Text.Length - tmpStart;
}
// Reset lenth
length = length - tmpLenth;
if (tmpLenth == 0)
break;
// Remove substring from current run
run.Text = run.Text.Remove(tmpStart, tmpLenth);
}
}
// Save output document
doc.Save(@"Test065\out.doc");


Hope this helps.
Best regards.

Hi,

Thanks for that. Does this only work per paragraph? Can I apply it to the entire document - as I won’t know the section or paragraph.

Thanks Bruce

Hi
Thanks for your request. You can try using the following:

// Get Runs from the document
NodeCollection runs = doc.GetChildNodes(NodeType.Run, true);
int currentPosition = 0;
foreach (Run run in runs)
{


However, note this code will not remove paragraph or section breaks. If you need to do that, you can modify this code.
Best regards.