What is the alternative of String.Contains() method in J2ME? - java-me

I want to compare if string1 "stack" is in string2 "Welcome to stack overflow".
How to achieve this in J2ME?

.contains() is worked for that. Why are you looking for alternative? But here is the same code which achieves if a string contains a substring;
if( string.indexOf("stack") >= 0 ) { // True
}else {
}
In anywhere of string, that search the "stack" and returns true or false.

Related

How to set an empty or not empty entry for a switch case statement?

I'd like to know to set an entry to validate if a String is empty or not empty in a switch-case statement. Let me show you:
String str = 'value'
switch(str){
case str == '':
println('Entered an empty value')
break
case str != '':
println('Entered value '+str)
break
case 'CoDe':
println('Entered special code '+str)
break
default:
println('Incorrect entry')
break
}
I know how to set an entry with a value (case 3) but I don't know how to set a entry with an empty or not empty string value.
Any help?
I tested it, and I think I have the answer for you.
switch(str) {
case "": // empty
println("Entered an empty value")
break
case "CoDe": // str == CoDe
println("Entered special code "+str)
break
default: // String not empty and not "CoDe"
println("Not empty")
break
}
It works because you have case "" which is the empty string. Meaning that everithing else is not empty. everything else is the default:
If you are not convinced, I'll give you a different example with the same meaning.
if (str.isEmpty()) {
// do something
} else if (!str.isEmpty()) { // <- this if is redundant
// do something else
}
You don't need the second if, because, you enter the else branch only if str is not empty! I appleid the same logic to the case. And it works because case "": in Java is valid.
As commented, what you need in Java is a series of if tests.
In the String class, you can test either:
The string has no characters at all (isEmpty)
The string has no characters OR has only whitespace characters (isBlank)
if ( str.isEmpty() ) { System.out.println( "ERROR - String has no characters." ); }
else if ( str.isBlank() ) { System.out.println( "ERROR - String has only whitespace." ); }
else if ( str.equals( "CoDe" ) ) { System.out.println( "Code received." ); }
else { System.out.println( "ERROR - Incorrect entry." ); }
See that code run live at Ideone.com.
Before that code block, I would add a null-check.
Objects.requireNonNull( str ); // Throw exception if null.
I find the if - else if - else construct in Java to be awkward in terms of readability. The switch syntax is much better at making obvious that a series of possibilities is being tested, mutually-exclusive, with a single result.
I do wish Java offered a cascading test for a series of boolean expressions. I have used such a feature in another language. There I found the cascading-boolean-tests to be quite practical for handling a series of business rules. But, alas, no such feature in Java. If only Brian Goetz were taking my calls.
I do not know Groovy. Perhaps Groovy provides another facility.
Your code has a smell, as str != '' would block all further cases.
I would re-organize it and use straight-forward basic Groovy switch-statement:
String str = 'value'
switch(str){
case 'CoDe':
println "Entered special code $str"
break
case '':
println 'Entered an empty value'
break
case { str != '' && str != null }:
println "Entered value $str"
break
default:
println 'Incorrect entry'
}
prints
Entered value value

Making sure every Alphabet is in a string (Kotlin)

So I have a question where I am checking if a string has every letter of the alphabet in it. I was able to check if there is alphabet in the string, but I'm not sure how to check if there is EVERY alphabet in said string. Here's the code
fun isPangram (pangram: Array<String>) : String {
var panString : String
var outcome = ""
for (i in pangram.indices){
panString = pangram[i]
if (panString.matches(".^*[a-z].*".toRegex())){
outcome = outcome.plus('1')
}
else {outcome = outcome.plus('0')}
}
return outcome
}
Any ideas are welcomed Thanks.
I think it would be easier to check if all members of the alphabet range are in each string than to use Regex:
fun isPangram(pangram: Array<String>): String =
pangram.joinToString("") { inputString ->
when {
('a'..'z').all { it in inputString.lowercase() } -> "1"
else -> "0"
}
}
Hi this is how you can make with regular expression
Kotlin Syntax
fun isStrinfContainsAllAlphabeta( input: String) {
return input.lowercase()
.replace("[^a-z]".toRegex(), "")
.replace("(.)(?=.*\\1)".toRegex(), "")
.length == 26;
}
In java:
public static boolean isStrinfContainsAllAlphabeta(String input) {
return input.toLowerCase()
.replace("[^a-z]", "")
.replace("(.)(?=.*\\1)", "")
.length() == 26;
}
the function takes only one string. The first "replaceAll" removes all the non-alphabet characters, The second one removes the duplicated character, then you check how many characters remained.
Just to bounce off Tenfour04's solution, if you write two functions (one for the pangram check, one for processing the array) I feel like you can make it a little more readable, since they're really two separate tasks. (This is partly an excuse to show you some Kotlin tricks!)
val String.isPangram get() = ('a'..'z').all { this.contains(it, ignoreCase = true) }
fun checkPangrams(strings: Array<String>) =
strings.joinToString("") { if (it.isPangram) "1" else "0" }
You could use an extension function instead of an extension property (so it.isPangram()), or just a plain function with a parameter (isPangram(it)), but you can write stuff that almost reads like English, if you want!

Lua strings 'n' things

New to Lua, need to check if a string exists inside another string, and can't seem to figure it out, how do I?
In PHP this'd be:
<?php
$pos = strpos($haystack,$needle);
if($pos === false) {
// string needle NOT found in haystack
} else {
// string needle found in haystack
}
?>
Also need to chop off the last char of a string...
http://lua-users.org/wiki/StringLibraryTutorial
print(string.find("foobar", "foo"))
yields...
1 3
print(string.find("foobar", "baz"))
yields...
nil
print(string.sub("foobar", 1, 5))
yields...
fooba
For chopping the last character, you can use a negative index:
string.sub("the string.", 1, -2)

Is there a .NET function to remove the first (and only the first) occurrence at the start of a string?

I was using the TrimStart function to do the following:
var example = "Savings:Save 20% on this stuff";
example = example.TrimStart("Savings:".ToCharArray());
I was expecting this to result in example having a value of "Save 20% on this stuff".
However, what I got was "e 20% on this stuff".
After reading the documentation on TrimStart I understand why, but now I'm left wondering if there is a function in .NET that does what I was trying to do in the first place?
Does anyone know of a function so I don't have to create my own and keep track of it?
I don't think such a method exists but you can easily do it using StartsWith and Substring:
s = s.StartsWith(toRemove) ? s.Substring(toRemove.Length) : s;
You can even add it as an extension method:
public static class StringExtension
{
public static string RemoveFromStart(this string s, string toRemove)
{
if (s == null)
{
throw new ArgumentNullException("s");
}
if (toRemove == null)
{
throw new ArgumentNullException("toRemove");
}
if (!s.StartsWith(toRemove))
{
return s;
}
return s.Substring(toRemove.Length);
}
}
No, I don't believe there's anything which does this built into the framework. It's a somewhat unusual requirement, IMO.
Note that you should think carefully about whether you're trying to remove "the first occurrence" or remove the occurrence at the start of the string, if there is one. For example, think what you'd want to do with: "Hello. Savings: Save 20% on this stuff".
You can do that quite easily using a regular expression.
Remove the occurrence on the beginning of the string:
example = Regex.Replace(example, #"^Savings:", "");
Remove the first occurrence in the string:
example = Regex.Replace(example, #"(?<!Savings:.*)Savings:", "");

Comparing sentences (strings) in AS3

I'm building a short quiz where the user needs to input the meaning of an acronym.
This means I need to compare a long string (usually a sentence) typed in by the user with an acronym.
I have a feeling I'm not doing it right. For my testing I'm copy-pasting the correct answer to make sure the spelling is correct however I keep getting the feedback that the answer is incorrect.
My question is, am I comparing correctly?
Here's my code:
var arrQuestions:Array = [["LOL","Laughing Out Loud"], ["OMG", "Oh My God"], ["BTW", "By The Way"]];
var i:Number=0;
function setup():void {
quiztext_txt.text = arrQuestions[i][0];
trace(quiztext_txt.text);
trace(arrQuestions[i][1]);
check_btn.addEventListener(MouseEvent.CLICK, clickHandler);
}//End of Setup()
setup();
function clickHandler(event:MouseEvent):void {
var givenString:String;
var inputString:String;
inputString = userinput_txt.text;
givenString = arrQuestions[i][1];
if (inputString == givenString) {
feedback_txt.text = "Correct!";
} else {
feedback_txt.text = "Wrong!";
}
}
Is there any whitespace before/after the user input? Is the value of i changing in between?
else
{
//what does it trace?
trace("given answer: " + inputString + "\ncorrect answer: " + givenString);
feedback_txt.text = "Wrong!";
}
try clearing the text field in your setup function like so:
function setup():void
{
userinput_txt.text = "";
quiztext_txt.text = arrQuestions[i][0];
trace(quiztext_txt.text);
trace(arrQuestions[i][1]);
check_btn.addEventListener(MouseEvent.CLICK, clickHandler);
}//End of Setup()
For any kind of string matching I would strongly recommend looking into regular expressions (RegExp). In the regular expression written below I am matching each word, then I say [ ]+ which means "at least one or more spaces", then at the end of the expression I use /gi to say that the expression is case insensitive. In the code above if I type the phrase in lowercase its not going to match, a quick fix for this would be to use this if(inputString.toLowerCase() == givenString.toLowerCase()) which would catch this. Heres the regexp example:
// testString could easily equal myTextField.text
var testString:String = "lauGHing OuT loUD";
// you could store each one in an array, as you were before
var regEx:RegExp = /laughing[ ]+out[ ]+loud/gi
trace( regEx.test( testString ) ); //returns true,test() returns a Boolean
Hope this helps.

Resources