# How to get x,y coordinates of a substring?

Hello all,

I’m building an app that requires me to know the xy coordinates of certain words or phrases within a body of text. My approach has been reasonably successful, but not nearly as precise as I’d like.

Here is the function I created to output the coordinates of a particular substring. It takes as input the index of the first letter of the substring. The function counts the number of line breaks before the substring occurs, and multiplies that value by “getLineHeight()” to approximate the y value of the substring. For the x value, the distance (in number of characters) from the left margin is multiplied by “getSize()”. Note that I set the initial x and y values of the “coors” vector to account for the horizontal and vertical margin I applied to the body of text:

``````
ofVec3f testApp::getTokenCoors(int index) {
ofVec3f coors;
coors.x = textMargin.x;
coors.y = textMargin.y;

int numBreaks = 0;
int start = 0;

while(source.find("\n", start+2) < index) {
start = source.find("\n", start+2);
numBreaks++;
}

int distX = index - (start+1);

coors.x += textFont.getSize() * distX;
coors.y += textFont.getLineHeight() * numBreaks;

return coors;
}

``````

Is there something I’m not accounting for? I’ve noticed that as “distX” increases, the resulting x coordinate becomes less accurate, meaning it increasingly overshoots the target x value. Am I underestimating the variation in the width of each character, and if so, is there a way to get the width of a specific character? I’m using Garamond, which isn’t a monospace font after all.

Thanks, and let me know if I can clarify something.