„Java“ programa, skirta patikrinti, ar eilutėje yra poskyris

Šiame pavyzdyje mes išmoksime patikrinti, ar eilutėje yra poskyris, naudojant Java metodą

Norėdami suprasti šį pavyzdį, turite žinoti šias Java programavimo temas:

  • „Java“ eilutė
  • „Java“ eilutės pakategorė ()

1 pavyzdys: Patikrinkite, ar eilutėje yra eilutė, naudodami

 class Main ( public static void main(String() args) ( // create a string String txt = "This is Programiz"; String str1 = "Programiz"; String str2 = "Programming"; // check if name is present in txt // using contains() boolean result = txt.contains(str1); if(result) ( System.out.println(str1 + " is present in the string."); ) else ( System.out.println(str1 + " is not present in the string."); ) result = txt.contains(str2); if(result) ( System.out.println(str2 + " is present in the string."); ) else ( System.out.println(str2 + " is not present in the string."); ) ) )

Rezultatas

Eilutėje yra „Programiz“. Programavimo eilutėje nėra.

Ankstesniame pavyzdyje mes turime tris eilutes txt, str1 ir str2. Norėdami patikrinti, ar eilutės str1 ir str2 yra txt, mes naudojome metodą String sees ().

2 pavyzdys: naudodami indexOf () patikrinkite, ar eilutėje yra eilutė

 class Main ( public static void main(String() args) ( // create a string String txt = "This is Programiz"; String str1 = "Programiz"; String str2 = "Programming"; // check if str1 is present in txt // using indexOf() int result = txt.indexOf(str1); if(result == -1) ( System.out.println(str1 + " not is present in the string."); ) else ( System.out.println(str1 + " is present in the string."); ) // check if str2 is present in txt // using indexOf() result = txt.indexOf(str2); if(result == -1) ( System.out.println(str2 + " is not present in the string."); ) else ( System.out.println(str2 + " is present in the string."); ) ) )

Rezultatas

Eilutėje yra „Programiz“. Programavimo eilutėje nėra.

Šiame pavyzdyje mes naudojome String indexOf () metodą, norėdami rasti eilutės str1 ir str2 padėtį txt. Jei rasta eilutė, grąžinama eilutės padėtis. Priešingu atveju grąžinama -1 .

Įdomios straipsniai...