searching a string with indexOf(

I have a string of text that I'm trying to locate the periods, so I do string.indexOf("."); to get the index value. It returns to correct position when the text looks like this:

The cat is here.

but the index is off by one when the text looks like this:

The cat is here

.

Every time when I space it down the index returned is thrown off, what should I do?

[393 byte] By [jpeanuta] at [2007-11-27 3:27:36]
# 1
your calculated index is correct. The carriage return is counted as a character.
petes1234a at 2007-7-12 8:30:23 > top of Java-index,Desktop,Core GUI APIs...
# 2

To show you what I mean, run this short app (or better yet, put your strings through this showStr routine). You'll see the ascii character value for linefeed (10) just before the value for period (46).

class Fubar

{

private static String showStr(String s)

{

StringBuilder sb = new StringBuilder();

for (int i = 0; i < s.length(); i++)

{

char schr = s.charAt(i);

Integer sInt = new Integer((int)schr);

sb.append(sInt.toString());

if (i != s.length() - 1)

{

sb.append(" ");

}

}

return sb.toString();

}

public static void main(String[] args)

{

String NmlStr = "The ball is red.";

String StrWCR = "The ball is red\n.";

System.out.println("chars in: " + NmlStr);

System.out.println("" + showStr(NmlStr));

System.out.println("chars in: " + StrWCR);

System.out.println("" + showStr(StrWCR));

}

}

petes1234a at 2007-7-12 8:30:23 > top of Java-index,Desktop,Core GUI APIs...
# 3
I see, but is there a method to ignore the return, because when it refer to the index value I found to color the text, it does not include the return, so my coloring becomes off by one.
jpeanuta at 2007-7-12 8:30:23 > top of Java-index,Desktop,Core GUI APIs...
# 4

> I see, but is there a method to ignore the return,

> because when it refer to the index value I found to

> color the text, it does not include the return, so my

> coloring becomes off by one.

Can you show us your code? Let's see what you are trying to do and if their's a way to work around it.

/Pete

petes1234a at 2007-7-12 8:30:23 > top of Java-index,Desktop,Core GUI APIs...
# 5

> I see, but is there a method to ignore the return,

Well, it sounds like you are getting your String from a text component using:

textComponent.getText();

In this case the String will return two characters to represent the newline String in a Windows environment. However, when you go to highlight the text in the text component the Document only uses a single character to represent the newline String which is why you are off by 1 for every line in the file.

The solution is to use:

textComponent.getDocument().getText(...);

then the returned string will only contain a single character for the newline String.

camickra at 2007-7-12 8:30:23 > top of Java-index,Desktop,Core GUI APIs...