Abo Hani Abo Hani - 1 month ago 6
Java Question

Check if letter x is between two brackets

I'd like to check if some character is between 2 other chars.

For example, given the following String:

String myString = "Hello, my name is 'Tesda', and this is 'ASDfs'."


I want to check if the
'S'
in
"ASDfs"
is between
''
or not, also keeping in mind I want to check every
''
, not jump directly to the second
''
.

I've tried a silly code (I'm not familiar with this at all, as I didn't need it until now), which is:

boolean isBetween;

if (!MyString.substring(MyString.indexOf("'"), MyString.indexOf("'")).contains("S"))
isBetween = true;


Well, this didn't work and I don't understand how to make it perfectly.

Also, I want to replace that S with another letter, but I want only between the
''
, not the one after
"my name is"
, I thought about getting the index of the letter, if it's inside
''
, then replace that letter in that specific index, is that possible?

Using the provided answer, I've made the following code ( which why i posted this question for ) :

String NewText = "Hello, My NAme is 'Ba', i'm from 'LA' ";
boolean contains = false;
int indexOfS = -1;

String MyString_temp = NewText;

while (MyString_temp.length() >= 0) {
int first = MyString_temp.indexOf("\'");
if(first == -1)
{
break;
}
int second = MyString_temp.substring((first + 1)).indexOf("\'");
second = second + first + 1;
if(second == -1)
{
break;
}
contains = MyString_temp.substring(first,second).contains("A");
if (contains) {
break;
}
MyString_temp = MyString_temp.substring((second + 1));
}

Log.i("ResultTest","Index is: " + indexOfS + " - Text is: " + MyString_temp);


if(!contains){
Log.i("ResultTest", "Yes " + i);
Log.i("ResultTest","TeF: " +NewText.replace(NewText.substring(indexOfS,indexOfS+1),"Test"));
} else
Log.i("ResultTest", "No " + i);


Output

Index is: -1 - the text here ..
Failed to output, invalid index

Answer

Consider using regular expressions. Your example could be as simple as

MyString.matches("\'S\'");

EDIT: Updated answer for updated question: Your initial code block looked like it might have done the trick, however you must remember that indexOf() only returns the first occurence of what you need. This could work:

String MyString_temp = MyString;
boolean contains = false;
int indexOfS = -1;

while (MyString_temp.length() >= 0) {
   int first = MyString_temp.indexOf("\'");
   if(first == -1)
   {
       break;
   }
   int second = MyString_temp.substring((first + 1)).indexOf("\'");
   second = second + first + 1;
   if(second == -1)
   {
       break;
   }
   indexOfS = MyString_temp.substring(first,second).indexOf("S");
   contains = (indexOfS >= 0)
   if (contains) {
      break;
   }
   MyString_temp = MyString_temp.substring((second + 1));
}

After the while loop, contains has your answer, and indexOfS has the location of S.

Comments