Wednesday, March 28, 2012

Substring of text...

OK, this probably is a question with a very simple answer, though I seem to be unable to find it... I'm creating my own weblog at the moment, and on the main page I would like to put a substring of the day's text ,until the first dot.

This is the code I've been trying to use :

Dim logText As String = qWebLog.myDataReader("msgText")
logText = logText.Substring(0, logText.indexOf("."))
logBodyCell.Text = logText & " <a href='?logID=" & qWebLog.myDataReader("ID") _
& "'>Read more ...</a>"

To illustrate : it should put the text in the cell till the first occurence of the dot (the end of the first sentence in other words... Though this code doesn't work, he gives the following error : length cannot be less than zero : paramatername = length.

Though, the text contains a dot ...

Who could help me please?

Regards,
NielsThe text cannot contain a dot if the error is occuring. I would suggest that you do the following:

String logText = qWebLog.myDataReader("msgText");

Int IndexOfDot = logText.IndexOf(".");

if (IndexOfDot > -1) {

logText = logText.Substring(0, IndexOfDot);
}

logBodyCell.Text = logText + " <a href='?logID=" + qWebLog.myDataReader("ID") + "'>Read more ...</a>";


Thanks a lot ! That worked ...

But now (sorry for my questioning...) I have the same problem when I type three dots... I tried it the same way :


Dim logText As String = qWebLog.myDataReader("msgText")
Dim IndexOfDot As Integer = logText.IndexOf(".")
Dim IndexOfTripleDot As Integer = logText.IndexOf("...")
If IndexOfDot > -1 Then
logText = logText.Substring(0, IndexOfDot + 1)
logBodyCell.Text = logText & " <a href='?logID=" & qWebLog.myDataReader("ID") _
& "'>Read more ...</a>"
ElseIf IndexOfTripleDot > -1 Then
logText = logText.Substring(0, IndexOfTripleDot + 1)
logBodyCell.Text = logText & " <a href='?logID=" & qWebLog.myDataReader("ID") _
& "'>Read more ...</a>"
Else
logBodyCell.Text = logText & " <a href='?logID=" & qWebLog.myDataReader("ID") _
& "'>Read more ...</a>"
End If

And it still doesn't work...

Sorry for the silly questions ...

Regards and a early happy newyear !

Regards
IndexOfDot will always be greater the -1 if IndexOfTripleDot is greater than -1, therefore the second condition will never be tested. Reverse the order of your if statements.

Also, you have six lines that do exactly the same thing. The following will achieve the same result, but with less lines of code:

Dim logText As String = qWebLog.myDataReader("msgText")

Dim IndexOfDot As Integer = logText.IndexOf(".")
Dim IndexOfTripleDot As Integer = logText.IndexOf("...")

If IndexOfTripleDot > -1 Then
logText = logText.Substring(0, IndexOfTripleDot + 1)
ElseIf IndexOfDot > -1 Then
logText = logText.Substring(0, IndexOfDot + 1)
End If

logBodyCell.Text = logText & " <a href='?logID=" & qWebLog.myDataReader("ID") _
& "'>Read more ...</a>"

0 comments:

Post a Comment