def search_substring(s, sub): for i in range(len(s) - len(sub) + 1): if s[i:i+len(sub)] == sub: return i return -1 s = "Hello, world!" sub = "world" result = search_substring(s, sub) if result != -1: print(f"Substring found at index {result}") else: print("Substring not found")
Pascal:
program SearchSubstring; function searchSubstring(s: string; sub: string): integer; var i: integer; begin for i := 1 to length(s) - length(sub) + 1 do begin if copy(s, i, length(sub)) = sub then begin searchSubstring := i; exit; end; end; searchSubstring := -1; end; var s, sub: string; result: integer; begin s := 'Hello, world!'; sub := 'world'; result := searchSubstring(s, sub); if result <> -1 then writeln('Substring found at index ', result) else writeln('Substring not found'); end.
C++:
#include <iostream> #include <string> int searchSubstring(std::string s, std::string sub) { for (int i = 0; i < s.length() - sub.length() + 1; i++) { if (s.substr(i, sub.length()) == sub) { return i; } } return -1; } int main() { std::string s = "Hello, world!"; std::string sub = "world"; int result = searchSubstring(s, sub); if (result != -1) { std::cout << "Substring found at index " << result << std::endl; } else { std::cout << "Substring not found" << std::endl; } return 0; }
Python:
def search_substring(s, sub):for i in range(len(s) - len(sub) + 1):
if s[i:i+len(sub)] == sub:
return i
return -1
s = "Hello, world!"
sub = "world"
result = search_substring(s, sub)
if result != -1:
print(f"Substring found at index {result}")
else:
print("Substring not found")
Pascal:
program SearchSubstring;function searchSubstring(s: string; sub: string): integer;
var
i: integer;
begin
for i := 1 to length(s) - length(sub) + 1 do
begin
if copy(s, i, length(sub)) = sub then
begin
searchSubstring := i;
exit;
end;
end;
searchSubstring := -1;
end;
var
s, sub: string;
result: integer;
begin
s := 'Hello, world!';
sub := 'world';
result := searchSubstring(s, sub);
if result <> -1 then
writeln('Substring found at index ', result)
else
writeln('Substring not found');
end.
C++:
#include <iostream>#include <string>
int searchSubstring(std::string s, std::string sub) {
for (int i = 0; i < s.length() - sub.length() + 1; i++) {
if (s.substr(i, sub.length()) == sub) {
return i;
}
}
return -1;
}
int main() {
std::string s = "Hello, world!";
std::string sub = "world";
int result = searchSubstring(s, sub);
if (result != -1) {
std::cout << "Substring found at index " << result << std::endl;
} else {
std::cout << "Substring not found" << std::endl;
}
return 0;
}