Comprobar si una string es una substring de otra

Dadas dos strings s1 y s2, encuentre si s1 es una substring de s2. En caso afirmativo, devuelve el índice de la primera aparición, de lo contrario, devuelve -1.

Ejemplos: 

C++

// C++ program to check if a string is
// substring of other.
#include <bits/stdc++.h>
using namespace std;
 
// Returns true if s1 is substring of s2
int isSubstring(string s1, string s2)
{
    int M = s1.length();
    int N = s2.length();
 
    /* A loop to slide pat[] one by one */
    for (int i = 0; i <= N - M; i++) {
        int j;
 
        /* For current index i, check for
 pattern match */
        for (j = 0; j < M; j++)
            if (s2[i + j] != s1[j])
                break;
 
        if (j == M)
            return i;
    }
 
    return -1;
}
 
/* Driver code */
int main()
{
    string s1 = "for";
    string s2 = "geeksforgeeks";
    int res = isSubstring(s1, s2);
    if (res == -1)
        cout << "Not present";
    else
        cout << "Present at index " << res;
    return 0;
}

Java

// Java program to check if a string is
// substring of other.
class GFG {
 
    // Returns true if s1 is substring of s2
    static int isSubstring(
        String s1, String s2)
    {
        int M = s1.length();
        int N = s2.length();
 
        /* A loop to slide pat[] one by one */
        for (int i = 0; i <= N - M; i++) {
            int j;
 
            /* For current index i, check for
            pattern match */
            for (j = 0; j < M; j++)
                if (s2.charAt(i + j)
                    != s1.charAt(j))
                    break;
 
            if (j == M)
                return i;
        }
 
        return -1;
    }
 
    /* Driver code */
    public static void main(String args[])
    {
        String s1 = "for";
        String s2 = "geeksforgeeks";
 
        int res = isSubstring(s1, s2);
 
        if (res == -1)
            System.out.println("Not present");
        else
            System.out.println(
                "Present at index "
                + res);
    }
}
 
// This code is contributed by JaideepPyne.

Python3

# Python3 program to check if
# a string is substring of other.
 
# Returns true if s1 is substring of s2
def isSubstring(s1, s2):
    M = len(s1)
    N = len(s2)
 
    # A loop to slide pat[] one by one
    for i in range(N - M + 1):
 
        # For current index i,
        # check for pattern match
        for j in range(M):
            if (s2[i + j] != s1[j]):
                break
             
        if j + 1 == M :
            return i
 
    return -1
 
# Driver Code
if __name__ == "__main__":
    s1 = "for"
    s2 = "geeksforgeeks"
    res = isSubstring(s1, s2)
    if res == -1 :
        print("Not present")
    else:
        print("Present at index " + str(res))
 
# This code is contributed by ChitraNayal

C#

// C# program to check if a string is
// substring of other.
using System;
class GFG {
 
    // Returns true if s1 is substring of s2
    static int isSubstring(string s1, string s2)
    {
        int M = s1.Length;
        int N = s2.Length;
 
        /* A loop to slide pat[] one by one */
        for (int i = 0; i <= N - M; i++) {
            int j;
 
            /* For current index i, check for
            pattern match */
            for (j = 0; j < M; j++)
                if (s2[i + j] != s1[j])
                    break;
 
            if (j == M)
                return i;
        }
 
        return -1;
    }
 
    /* Driver code */
    public static void Main()
    {
        string s1 = "for";
        string s2 = "geeksforgeeks";
 
        int res = isSubstring(s1, s2);
 
        if (res == -1)
            Console.Write("Not present");
        else
            Console.Write("Present at index "
                          + res);
    }
}
 
// This code is contributed by nitin mittal.

PHP

<?php
// PHP program to check if a
// string is substring of other.
 
// Returns true if s1 is substring of s2
function isSubstring($s1, $s2)
{
    $M = strlen($s1);
    $N = strlen($s2);
 
    // A loop to slide
    // pat[] one by one
    for ($i = 0; $i <= $N - $M; $i++)
    {
        $j = 0;
 
        // For current index i,
        // check for pattern match
        for (; $j < $M; $j++)
            if ($s2[$i + $j] != $s1[$j])
                break;
 
        if ($j == $M)
            return $i;
    }
 
    return -1;
}
 
// Driver Code
$s1 = "for";
$s2 = "geeksforgeeks";
$res = isSubstring($s1, $s2);
if ($res == -1)
    echo "Not present";
else
    echo "Present at index " . $res;
 
// This code is contributed by mits
?>

Javascript

<script>
 
// JavaScript program to check if a string is
// substring of other.
 
// Returns true if s1 is substring of s2
function isSubstring(s1, s2)
{
    var M = s1.length;
    var N = s2.length;
 
    /* A loop to slide pat[] one by one */
    for (var i = 0; i <= N - M; i++) {
        var j;
 
        /* For current index i, check for
 pattern match */
        for (j = 0; j < M; j++)
            if (s2[i + j] != s1[j])
                break;
 
        if (j == M)
            return i;
    }
 
    return -1;
}
 
/* Driver code */
var s1 = "for";
var s2 = "geeksforgeeks";
var res = isSubstring(s1, s2);
if (res == -1)
    document.write( "Not present");
else
    document.write( "Present at index " + res);
 
</script>

C++

#include <bits/stdc++.h>
using namespace std;
 
int Substr(string s2, string s1)
{
    int counter = 0; // pointing s2
    int i = 0;
    for(;i<s1.length();i++)
    {
        if(counter==s2.length())
            break;
        if(s2[counter]==s1[i])
        {
            counter++;
        }
      else
        {
            // Special case where character preceding the i'th character is duplicate
            if(counter > 0)
            {
                i -= counter;
            }
            counter = 0;
        }
    }
    return counter < s2.length()?-1:i-counter;
}
 
// Driver code
int main()
{
    string s1 = "geeksforgeeks";
    cout << Substr("for", s1);
    return 0;
}
 
// this code is contributed by Manu Pathria

Java

import java.io.*;
 
class GFG {
   public static int Substr(String s2, String s1){
        int counter = 0; //pointing s2
        int i = 0;
        for(;i<s1.length();i++){
            if(counter==s2.length())
                break;
            if(s2.charAt(counter)==s1.charAt(i)){
                counter++;
            }else{
                //Special case where character preceding the i'th character is duplicate
                if(counter>0){
                    i -= counter;
                }
                counter = 0;
            }
        }
        return counter < s2.length()?-1:i-counter;
    }
    public static void main (String[] args) {
        String s1 = "geeksforgeeks";
        //System.out.println(s2.indexOf("for"));
        System.out.println(Substr("for", s1));
    }
}

Python3

# Python program for the above approach
def Substr(s1, s2):
 
    counter = 0
    i = 0
    Len = len(s1)
 
    while(i < Len):
        if(counter == len(s2)):
            break;
        if(s2[counter] == s1[i]):
          counter += 1
        else:
          if(counter > 0):
            i -= counter
          counter = 0
        i += 1
 
    if (counter < len(s2)):
      return -1
    else:
      return (i - counter)
 
 
# Driver code
print(Substr("geeksforgeeks", "for"))
 
# This code is contributed by avanitrachhadiya2155

C#

//  C# program for the above approach
using System;
class GFG {
  static int Substr(string s2, string s1)
  {
    int counter = 0; // pointing s2
    int i = 0;
    for (; i < s1.Length; i++) {
      if (counter == s2.Length)
        break;
      if (s2[counter] == s1[i]) {
        counter++;
      }
      else {
 
        // Special case where character preceding
        // the i'th character is duplicate
        if (counter > 0) {
          i -= counter;
        }
        counter = 0;
      }
    }
    return counter < s2.Length ? -1 : i - counter;
  }
 
  // Driver code
  public static int Main()
  {
    string s1 = "geeksforgeeks";
    Console.Write(Substr("for", s1));
    return 0;
  }
}
 
// This code is contributed by Taranpreet

Javascript

<!-- Javascript program for the above approach -->
 
<script>
   function Substr( s2,  s1){
    
    var counter = 0; // pointing s2
    var i = 0;
    for( ;i < s1.length; i++)
    {
        if( counter == s2.length )
        {
            break;
        }
        if( s2[counter] == s1[i] )
        {
            counter++;
        }
      else
        {
            // Special case where character preceding
            // the i'th character is duplicate
            if(counter > 0)
            {
                i -= counter;
            }
            counter = 0;
        }
    }
    
    return counter < s2.length ? -1 : i-counter;
}
  
 
// Driver code
 var s1 = "geeksforgeeks";
 document.write(Substr("for", s1));
  
</script>
 
<!-- this code is contributed by Nirajgusain5 -->

C++

//C++ implementation of the approach
 
#include <bits/stdc++.h>
using namespace std;
 
// function to get the index of s2 in s1
int isSubstring(string s1, string s2)
{
    // using find method to check if s1 is
    // a substring of s2
    if (s2.find(s1) != string::npos)
        return s2.find(s1);
    return -1;
}
 
// Driver code
int main()
{
    string s1 = "for";
    string s2 = "geeksforgeeks";
   
      //Function Call
    int res = isSubstring(s1, s2);
    if (res == -1)
        cout << "Not present";
    else
        cout << "Present at index " << res;
    return 0;
}
 
// this code is contributed by phasing17

Python3

# Python3 program to check if
# a string is substring of other.
 
# Checks if s1 is a substring of s2
def isSubstring(s1, s2):
    if s1 in s2:
      return s2.index(s1)
    return -1
 
# Driver Code
if __name__ == "__main__":
    s1 = "for"
    s2 = "geeksforgeeks"
    res = isSubstring(s1, s2)
    if res == -1 :
        print("Not present")
    else:
        print("Present at index " + str(res))
 
# This code is contributed by phasing17

Java

//Java program to implement the approach
 
class GFG {
    // function to get the index of s2 in s1
    static int isSubstring(String s1, String s2)
    {
        // using indexOf method to check if s1 is
        // a substring of s2
        return s2.indexOf(s1);
    }
    public static void main(String[] args) {
        String s1 = "for";
        String s2 = "geeksforgeeks";
       
          //Function Call
        int res = isSubstring(s1, s2);
        if (res == -1)
            System.out.println("Not present");
        else
            System.out.println("Present at index " + res);
    }
}
 
//this code is contributed by phasing17

Javascript

//JS program to implement the approach
 
// function to get the index of s2 in s1
function isSubstring(s1, s2)
{
    // using indexOf method to check if s1 is
    // a substring of s2
    return s2.indexOf(s1);
}
 
// Driver code
var s1 = "for";
var s2 = "geeksforgeeks";
   
//Function Call
var res = isSubstring(s1, s2);
if (res == -1)
    console.log("Not present");
else
    console.log("Present at index " + res);
 
 
// this code is contributed by phasing17

C#

// C# program to implement the approach
 
using System;
 
public class GFG {
    // function to get the index of s2 in s1
    static int isSubstring(string s1, string s2)
    {
        // using IndexOf method to check if s1 is
        // a substring of s2
        return s2.IndexOf(s1);
    }
    public static void Main(string[] args)
    {
        string s1 = "for";
        string s2 = "geeksforgeeks";
 
        // Function Call
        int res = isSubstring(s1, s2);
        if (res == -1)
            Console.WriteLine("Not present");
        else
            Console.WriteLine("Present at index " + res);
    }
}
 
// this code is contributed by phasing17

Publicación traducida automáticamente

Artículo escrito por kartik y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *