Finding a Substring Within a String Without Using Any Built in Functions

Finding a substring of a string in Python without inbuilt functions

def index(s, sub):
start = 0
end = 0
while start < len(s):
if s[start+end] != sub[end]:
start += 1
end = 0
continue
end += 1
if end == len(sub):
return start
return -1

Output:

>>> index("dedicate", 'cat')
4
>>> index("this is an example", 'example')
11
>>> index('hello world', 'word')
-1

Finding substring in string without using library function

  • Do not use gets(), which has unavoidable risk of buffer overrun.
  • The condition of the loop is wrong. The loop should exited if one of *(str + j) or *(substr + i) is a (terminating) null character.

Fixed code:

#include <stdio.h>
int findSubstring(char *str, char *substring);
void safer_gets(char *str, size_t max);
int main(void)
{
char str[40], substr[40];
printf("Enter the string: ");
safer_gets(str, sizeof(str));
printf("Enter the substring: ");
safer_gets(substr, sizeof(str));
printf("findSubstring(): %d\n", findSubstring(str, substr));
return 0;
}
int findSubstring(char *str, char *substr)
{
int i = 0, j = 0;
while ((*(str + j) != '\0')&&(*(substr + i) != '\0')) {
if (*(substr + i) != *(str + j)) {
j++;
i = 0;
}
else {
i++;
j++;
}
}
if (*(substr + i) == '\0')
return 1;
else
return -1;
}
void safer_gets(char *str, size_t max)
{
int i;
fgets(str, max, stdin);
for (i = 0; *(str + i) != '\0'; i++) {
if (*(str + i) == '\n') {
*(str + i) = '\0';
break;
}
}
}

Find substring in string without includes/indexOf/Regex in Javascript

Here is an optimized example of the algorythm isSubstring. It iterates only through the minimum number of characters required.

For example, if the string is 20 characters long and the substring is only 5 characters long, when we get to the 16th position of the string we can assume that the substring doesn't exist within the string (16 + 5 = 21 > 20)

function isSubstring(str, sub){  if(sub.length > str.length) return false;  for(let i = 0; i < str.length - sub.length + 1; i++){    if(str[i] !== sub[0]) continue;    let exists = true;    for(let j = 1; j < sub.length && exists; j++){        if(str[i+j] === sub[j]) continue;        exists = false;    }    if(exists) return true;  }  return false;}
//expected trueconsole.log(isSubstring("hello world", "hello"));console.log(isSubstring("hello world", "world"));console.log(isSubstring("hello world", "d"));console.log(isSubstring("hello world", "o w"));console.log(isSubstring("hello world", "rl"));console.log(isSubstring("hello world", ""));
//expected falseconsole.log(isSubstring("hello world", "hello world 1"));console.log(isSubstring("hello world", "helloo"));

Substring in c without using functions

There are a number of ways to recreate strstr. The following is a quick implementation using the inch-worm method, where you simply use pointers to search for the beginning of the substring in string, then if found, compare every character in substring with the corresponding character in string. If all characters match, the substring is found, return a pointer to the beginning of substring in string.

If a character fails the test, look for another character in string that matches the first character in substring, until string is exhausted.

There are probably several more checks that can be inplemented, but this example should get you started:

#include <stdio.h>
#include <stdlib.h>

char *strstr2 (char *str, char *sub)
{
if (!str || !sub) return NULL; /* validate both strings */

char *p = NULL; /* general pointer */
char *sp = NULL; /* substring pointer */
char *rp = NULL; /* return pointer */
char matched = 0; /* matched flag */
size_t szstr = 0; /* string length */
size_t szsub = 0; /* substring length */

p = sub;
while (*p++) szsub++; /* strlen of substr */

p = str;
while (*p++) szstr++; /* strlen of str */

if (szsub > szstr) return NULL; /* szstr < szsub - no match */

p = str;

while (p < (p + szstr - szsub + 1))
{
while (*p && *p != *sub) p++; /* find start of sub in str */

if ((str + szstr) == p) return NULL; /* if end reached - no sub */

rp = p; /* save return pointer */
sp = sub; /* set sp to sub */
matched = 1; /* presume will match */
while (*sp) /* for each in substring */
if (*p++ != *sp++) { /* check if match fails */
matched = 0; /* if failed, no match */
break; /* break & find new start */
}
if (matched) /* if matched, return ptr */
return rp; /* to start of sub in str */
}

return NULL; /* no match, return NULL */
}

int main() {

char *string = NULL;
char *substr = NULL;
char *begin = NULL;

printf ("\nEnter string : ");
scanf ("%m[^\n]%*c", &string);

printf ("\nEnter substr : ");
scanf ("%m[^\n]%*c", &substr);

if ((begin = strstr2 (string, substr)) != NULL)
printf ("\nSubstring found beginning at : %s\n\n", begin);
else
printf ("\nSubstring NOT in string.\n\n");

if (string) free (string);
if (substr) free (substr);

return 0;
}

output:

$ ./bin/strstr

Enter string : This is the full string or "haystack".

Enter substr : g or "

Substring found beginning at : g or "haystack".

$ ./bin/strstr

Enter string : This is the full string or "haystack".

Enter substr : g or '

Substring NOT in string.

Check if string contains substring without using any standard JavaScript methods?

You have a good solution. But I think mine is easier.

By the way: I think .length is a javascript funciton too.

function length(string){  var count = 0;  while(string[count] != undefined)     count++;  return count;}
function contains(masterString, subString) { var masterStringLength = length(masterString); var subStringLength = length(subString); for(var i = 0; i <= masterStringLength - subStringLength; i++) { var count = 0; for(var k = 0; k < subStringLength; k++) { if(masterString[i + k] == subString[k]) count++; else break; } if(count == subStringLength) return true;
} return false;}
console.log(contains('abcdefgh', 'bcde'));console.log(contains('abcdefgh', 'ab'));console.log(contains('abcdefgh', 'fgh'));

Occurrences of a substring in a string without using string functions [closed]

Assuming, you already know the keyword you are searching for:

  • Start at char "0" of Input String
  • Iterate until "length - keyWordLength" (keyword of length 4 can not match into the last 3 chars)
  • Inside: Iterate from 0 to keyWord.length -1 and always compare:
  • Char at Position of outer loop PLUS position of inner loop of the Input string with the char at "inner loops" position of the keyword.
  • if you find a match, go ahead with the innerloop, if it does not match, advance the outer loop, by simple "breaking" the inner loop.
  • If you have a match, and completely processed the inner loop, you have a match of that keyword.

Something like this. I'm Assuming String.length to be allowed. Otherwhise you would need to create your own strlen function. (This can be achieved, using a forach loop and simple counting "up")

This is untested and may not work out of the box, but should give you a brief idea.

String inputString = "knowbutuknow";
String subString = "know";

int matches = 0;
for (int outer = 0; outer <= inputString.length() - subString.length(); outer++){
for (int inner = 0; inner < subString.length(); inner++){
if (inputString.charAt(outer + inner) == subString.charAt(inner)){
// letter matched, proceed.
if (inner == subString.length()-1){
//last letter matched, so a word match at position "outer"
matches++;
//proceed with outer. Room for improvement: Skip next n chars beeing
// part of the match already.
break;
}
}else{
//no match for "outer" position, proceed to next char.
break;
}
}
}

edit: Sorry, mixed in some php :) fixed it.

making a substring from string in java without using any string function

Note that you're question is not very precise and hence your requirements are not very clear.

Simple way :

String st = new StringBuilder(s).substring(3,6); 

Or you can directly construct the new String using reflection to get the char array:

public static String substring(String s, int from, int to){
Field f = String.class.getDeclaredField("value");
f.setAccessible(true);
char [] tab = (char[])f.get(s);
f.setAccessible(false);
return new String(tab, from, to - from);
}



Those can also be options (note that it works only if the original String fits an hexadecimal format) :

String s ="abcfedbca";
BigInteger bi = new BigInteger(s, 16);
bi = bi.and(new BigInteger("16699392")); //0xfed000 in hexa
bi = bi.shiftRight(12);
System.out.println(bi.toString(16));

Or more simple :

String s ="abcfedbca";
System.out.println(Integer.toHexString((int)(Long.parseLong(s, 16) & 16699392) >> 12));

If you want a more general method, this one might suits your case :

public static void main(String [] args){
String s ="abcfedbca";
System.out.println(substring(s, 2, 5, 9));
}

public static String substring (String s, int from, int to, int length){
long shiftLeft = 0;
long shiftRight = (length - to - 1) * 4;
for(int i = 0; i < to - from - 1; i++){
shiftLeft += 15;
shiftLeft = shiftLeft << 4;
}
shiftLeft += 15;
return Long.toHexString((Long.parseLong(s, 16) & (shiftLeft << shiftRight)) >> shiftRight);
}


Related Topics



Leave a reply



Submit