I'm trying to make a simple function in dart to test on which should remove all vowels from an input string but its seems my code never changes the from the original input. Could anyone help me with this? thanks
String removeVowel( str) {
var toReturn = "";
for (var i = 0; i < str.length; i++) {
var temp = str.substring(i,i+1);
if (temp != 'a' || temp != 'e' || temp != 'i' || temp != 'o' || temp!= 'u')
{
toReturn = toReturn + temp;
}
}
return toReturn;
}
and what my tests shows:
00:02 +0 -1: dog --> dg [E]
Expected: 'dg'
Actual: 'dog'
Which: is different.
Expected: dg
Actual: dog
^
Differ at offset 1
Good first try but there is a much easier way of doing this.
replaceAll should do the trick
String removeVolwels(String s){
return s.replaceAll(RegExp('[aeiou]'),'');
}
https://api.flutter.dev/flutter/dart-core/String/replaceAll.html
To make your code work you should change the || to &&
String removeVowel( str) {
var toReturn = "";
for (var i = 0; i < str.length; i++) {
var temp = str.substring(i,i+1);
if (temp != 'a' && temp != 'e' && temp != 'i' && temp != 'o' && temp!= 'u')
{
toReturn = toReturn + temp;
}
}
return toReturn;
}
Related
string removeVowels(string s)
{
string c = "";
// Your code goes here
for(int i=0;i<s.length();i++){
if(s[i] != 'A'||s[i] != 'E'||s[i] != 'I'||s[i] !=
'O'||s[i] != 'U'||s[i] != 'a'||s[i] != 'e'||s[i]
!= 'i'||s[i] != 'o'||s[i] != 'u'){
c = c + s[i];
}
}
return c;
}
I have to some vowels from the string why this code not works
The loop keeps repeating the output for the entire span of the word.
I tried initiating the console.write on the inside and outside the loop. I also tried changing the values of the incrementor and the substring.
Console.WriteLine("Enter a word.");
string userWord = Console.ReadLine();
Console.WriteLine();
Console.WriteLine("You wrote {0}", userWord);
Console.WriteLine();
userWord.ToLower();
char[] wordArray = userWord.ToArray();
for (int i = 0; i <= wordArray.Length; i++)
{
string theLetter = userWord.Substring(i, 1);
//theLetter = theLetter.ToLower();
string rebuilt = new string(wordArray);
if (wordArray[i] == 'a' || wordArray[i] == 'e' || wordArray[i] == 'i' || wordArray[i] == 'o' || wordArray[i] == 'u')
{
wordArray[i] = '$';
}
Console.WriteLine("Your word is now: {0}", rebuilt);
Console.WriteLine("The total number of letters in your word is {0}", userWord.Length);
}
Console.ReadLine();
the console.write should display it's output only once.
You would need to move your Console.WriteLine outside the loop. Also, your loop condition needs to be changed to avoid the ArgumentOutOfRangeException.
for (int i = 0; i < wordArray.Length; i++)
There is one more error in your code. You are converting userWord to lower case, but you are not storing the result.
userWord.ToLower();
Above line needs to be replaced with
userWord = userWord.ToLower();
Complete Code
Console.WriteLine("Enter a word.");
string userWord = Console.ReadLine();
Console.WriteLine();
Console.WriteLine("You wrote {0}", userWord);
Console.WriteLine();
userWord = userWord.ToLower();
char[] wordArray = userWord.ToArray();
for (int i = 0; i < wordArray.Length; i++)
{
if (wordArray[i] == 'a' || wordArray[i] == 'e' || wordArray[i] == 'i' || wordArray[i] == 'o' || wordArray[i] == 'u')
{
wordArray[i] = '$';
}
}
var rebuildWord = new string(wordArray);
Console.WriteLine("Your word is now: {0}", rebuildWord);
Console.WriteLine("The total number of letters in your word is {0}", userWord.Length);
Just for your information, you could achieve the same using Regex as well.
Console.WriteLine("Enter a word.");
string userWord = Console.ReadLine();
Console.WriteLine();
Console.WriteLine("You wrote {0}", userWord);
Console.WriteLine();
var rebuildWord = Regex.Replace(userWord,#"[aeiouAEIOU]","$");
Console.WriteLine("Your word is now: {0}", rebuildWord);
Console.WriteLine("The total number of letters in your word is {0}", userWord.Length);
This is just simple. You should check if the loop is in final iteration before printing.
Console.WriteLine("Enter a word.");
string userWord = Console.ReadLine();
Console.WriteLine();
Console.WriteLine("You wrote {0}", userWord);
Console.WriteLine();
userWord.ToLower();
char[] wordArray = userWord.ToArray();
for (int i = 0; i <= wordArray.Length; i++)
{
string theLetter = userWord.Substring(i, 1);
//theLetter = theLetter.ToLower();
string rebuilt = new string(wordArray);
if (wordArray[i] == 'a' || wordArray[i] == 'e' || wordArray[i] == 'i' || wordArray[i] == 'o' || wordArray[i] == 'u')
{
wordArray[i] = '$';
}
if(i==userWord.Length)
{
Console.WriteLine("Your word is now: {0}", rebuilt);
Console.WriteLine("The total number of letters in your word is {0}", userWord.Length);
}
}
Console.ReadLine();
def binary_string(s):
Write a function that takes a string, converts it to a binary string
where vowels are replaced by 0 and consonants are replaced by 1.
The function should return the binary string.
binary_string("Karen")
'10101'
binary_string("Hello World!")
'10110 10111!'
if __name__ == '__main__':
import doctest
doctest.testmod(verbose = True)
Try something like this. Assuming the name of your string variable is "stringVar".
string binaryString="";
for(int i=0;i<stringVar.Length();i++)
{
if(stringVar == 'a' || stringVar == 'A' || stringVar == 'e') //and so on
{
binaryString[i] = '0';
}
else
{
binaryString[i] = '1';
}
}//end for loop.
print(binaryString);
This should give you the result you are looking for. This is the basic functionality. The rest depends on the language you are coding in.
Hope this helps.
Since you have not specified language in which you want solution, so i am assuming it to be java(from my side ). Although, algorithm will be valid for all languages.
code
public class SO {
public static void main(String[] args) {
String s = "Karen";
char[] arr = s.toCharArray();
StringBuilder binary = new StringBuilder();
for (char c : arr) {
if(Character.isAlphabetic(c)){
if (isVowel(c)) {
binary.append("0");
}else{
binary.append("1");
}
}else{
binary.append(c);
}
}
System.out.println(binary);
}
private static boolean isVowel(char c) {
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U') {
return true;
}
return false;
}
}
output
When input is
String s = "Karen";
then output is
binary = 10101
and
When input is
String s = "Hello World!";
then output is
binary = 10110 10111!
I am making a word game in unity3D game engine, I make a word if word spelling is wrong I want to remove a certain character from that word for making a correct spelling and then other character shift back... in my code I have an string and want to remove a char from string.... so that when the char is removed from the center of the string other char shift back.
static var nextPos = 200;
static var word: String;
var sel: String;
var isClicked : boolean=false;
var xpos: float = 200;
static var i:int=0;
function start()
{
word="";
}
function OnMouseDown()
{
if (!isClicked) {
isClicked = true;
xpos = nextPos;
sel=OnGUI();
word=word+sel;
nextPos += 8;
i++;
}
else if(isClicked)
{
isClicked = false;
xpos = nextPos;
nextPos -= 8;
}
}
function OnGUI()
{
if (gameObject.name == "Sphere(Clone)" && isClicked )
{
GUI.Label(new Rect(xpos,260,400,100), "A");
return "A";
}
else if (gameObject.name == "Sphere 1(Clone)" && isClicked )
{
GUI.Label(new Rect(xpos,260,400,100), "B");
return "B";
}
else if (gameObject.name == "Sphere 2(Clone)" && isClicked )
{
GUI.Label(new Rect(xpos,260,400,100), "C");
return "C";
}
GUI.Label(new Rect(xpos,280,400,100), "Value" + i);
GUI.Label(new Rect(xpos,300,400,100), word);
}
Test this:
string value = "abcde";
string temp="";
temp = value.Substring(0, position - 1);
value = temp + value.Substring(position, value.Length);
you can check which key is pressed once your text is being displayed
this should work . you need just call it in your update function or OnGUI function
set "word" as a global variable if you use it in an Update function
I wrote this out of my head , It should work , sorry it it has any glitches.
if(Input.anyKey)
{
string letter = Input.inputString;
if (word.Contains(letter))
{
word.Replace(letter,"");
}
}
Can someone explain to me how to solve the substring problem iteratively?
The problem: given two strings S=S1S2S3…Sn and T=T1T2T3…Tm, with m is less than or equal to n, determine if T is a substring of S.
Here's a list of string searching algorithms
Depending on your needs, a different algorithm may be a better fit, but Boyer-Moore is a popular choice.
A naive algorithm would be to test at each position 0 < i ≤ n-m of S if Si+1Si+2…Si+m=T1T2…Tm. For n=7 and m=5:
i=0: S1S2S3S4S5S6S7
| | | | |
T1T2T3T4T5
i=1: S1S2S3S4S5S6S7
| | | | |
T1T2T3T4T5
i=2: S1S2S3S4S5S6S7
| | | | |
T1T2T3T4T5
The algorithm in pseudo-code:
// we just need to test if n ≤ m
IF n > m:
// for each offset on that T can start to be substring of S
FOR i FROM 0 TO n-m:
// compare every character of T with the corresponding character in S plus the offset
FOR j FROM 1 TO m:
// if characters are equal
IF S[i+j] == T[j]:
// if we’re at the end of T, T is a substring of S
IF j == m:
RETURN true;
ENDIF;
ELSE:
BREAK;
ENDIF;
ENDFOR;
ENDFOR;
ENDIF;
RETURN false;
Not sure what language you're working in, but here's an example in C#. It's a roughly n2 algorithm, but it will get the job done.
bool IsSubstring (string s, string t)
{
for (int i = 0; i <= (s.Length - t.Length); i++)
{
bool found = true;
for (int j = 0; found && j < t.Length; j++)
{
if (s[i + j] != t[j])
found = false;
}
if (found)
return true;
}
return false;
}
if (T == string.Empty) return true;
for (int i = 0; i <= S.Length - T.Length; i++) {
for (int j = 0; j < T.Length; j++) {
if (S[i + j] == T[j]) {
if (j == (T.Length - 1)) return true;
}
else break;
}
}
return false;
It would go something like this:
m==0? return true
cs=0
ct=0
loop
cs>n-m? break
char at cs+ct in S==char at ct in T?
yes:
ct=ct+1
ct==m? return true
no:
ct=0
cs=cs+1
end loop
return false
This may be redundant with the above list of substring algorithms, but I was always amused by KMP (http://en.wikipedia.org/wiki/Knuth–Morris–Pratt_algorithm)
// runs in best case O(n) where no match, worst case O(n2) where strings match
var s = "hippopotumus"
var t = "tum"
for(var i=0;i<s.length;i++)
if(s[i]==t[0])
for(var ii=i,iii=0; iii<t.length && i<s.length; ii++, iii++){
if(s[ii]!=t[iii]) break
else if (iii==t.length-1) console.log("yay found it at index: "+i)
}
Here is my PHP variation that includes a check to make sure the Needle does not exceed the Haystacks length during the search.
<?php
function substring($haystack,$needle) {
if("" == $needle) { return true; }
echo "Haystack:\n$haystack\n";
echo "Needle:\n$needle\n";
for($i=0,$len=strlen($haystack);$i<$len;$i++){
if($needle[0] == $haystack[$i]) {
$found = true;
for($j=0,$slen=strlen($needle);$j<$slen;$j++) {
if($j >= $len) { return false; }
if($needle[$j] != $haystack[$i+$j]) {
$found = false;
continue;
}
}
if($found) {
echo " . . . . . . SUCCESS!!!! startPos: $i\n";
return true;
}
}
}
echo " . . . . . . FAILURE!\n" ;
return false;
}
assert(substring("haystack","hay"));
assert(!substring("ack","hoy"));
assert(substring("hayhayhay","hayhay"));
assert(substring("mucho22","22"));
assert(!substring("str","string"));
?>
Left in some echo's. Remove if they offend you!
Is a O(n*m) algorithm, where n and m are the size of each string.
In C# it would be something similar to:
public static bool IsSubtring(char[] strBigger, char[] strSmall)
{
int startBigger = 0;
while (startBigger <= strBigger.Length - strSmall.Length)
{
int i = startBigger, j = 0;
while (j < strSmall.Length && strSmall[j] == strBigger[i])
{
i++;
j++;
}
if (j == strSmall.Length)
return true;
startBigger++;
}
return false;
}
I know I'm late to the game but here is my version of it (in C#):
bool isSubString(string subString, string supraString)
{
for (int x = 0; x <= supraString.Length; x++)
{
int counter = 0;
if (subString[0] == supraString[x]) //find initial match
{
for (int y = 0; y <= subString.Length; y++)
{
if (subString[y] == supraString[y+x])
{
counter++;
if (counter == subString.Length)
{
return true;
}
}
}
}
}
return false;
}
Though its pretty old post, I am trying to answer it. Kindly correct me if anything is wrong,
package com.amaze.substring;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CheckSubstring {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter the main string");
String mainStr = br.readLine();
System.out.println("Enter the substring that has to be searched");
String subStr = br.readLine();
char[] mainArr = new char[mainStr.length()];
mainArr = mainStr.toCharArray();
char[] subArr = new char[subStr.length()];
subArr = subStr.toCharArray();
boolean tracing = false;
//System.out.println("Length of substring is "+subArr.length);
int j = 0;
for(int i=0; i<mainStr.length();i++){
if(!tracing){
if(mainArr[i] == subArr[j]){
tracing = true;
j++;
}
} else {
if (mainArr[i] == subArr[j]){
//System.out.println(mainArr[i]);
//System.out.println(subArr[j]);
j++;
System.out.println("Value of j is "+j);
if((j == subArr.length)){
System.out.println("SubString found");
return;
}
} else {
j=0;
tracing = false;
}
}
}
System.out.println("Substring not found");
}
}