How to Check If a String Is One of the Known Values

How to check if a string is one of the known values?

Use the in_array() function.

Manual says:

Searches haystack for needle using loose comparison unless strict is set.

Example:

<?php
$a = 'abc';

if (in_array($a, array('are','abc','xyz','lmn'))) {
echo "Got abc";
}
?>

How to check if the String object passed to the method contains at least one of the words from the list- JAVA

Looks like you are missing a condition to exit the loop when a forbidden word was found:

private static void wordsFilter(String sentence) {
List<String> forbiddenWords = new ArrayList<>();
forbiddenWords.add("forbiddenWord");
forbiddenWords.add("forbidden word");

boolean doesContainAnyForbiddenWords = false;

for (String word : forbiddenWords) {
if (sentence.contains(word)) {
doesContainAnyForbiddenWords = true;
break; // leave the loop
} else {
System.out.println(sentence);
}
}

if (doesContainAnyForbiddenWords) {
System.out.println("The content cannot be displayed");
} else {
System.out.println(sentence);
}
}

How do I check if a value matches a string

The short answer: strcmp().

The long answer: So you've got this:

if(players[i].sname == 'Lee')

This is wrong in several respects. First, single-quotes mean "character literal" not "string literal" in C.

Secondly, and more importantly, "string1" == "string2" doesn't compare strings, it compares char *s, or pointers to characters. It will tell you if two strings are stored in the same memory location. That would mean they're equal, but a false result wouldn't mean they're inequal.

strcmp() will basically go through and compare each character in the strings, stopping at the first character that isn't equal, and returning the difference between the two characters (which is why you have to say strcmp() == 0 or !strcmp() for equality).

Note also the functions strncmp() and memcmp(), which are similar to strcmp() but are safer.

Java String - See if a string contains only numbers and not letters

If you'll be processing the number as text, then change:

if (text.contains("[a-zA-Z]+") == false && text.length() > 2){

to:

if (text.matches("[0-9]+") && text.length() > 2) {

Instead of checking that the string doesn't contain alphabetic characters, check to be sure it contains only numerics.

If you actually want to use the numeric value, use Integer.parseInt() or Double.parseDouble() as others have explained below.


As a side note, it's generally considered bad practice to compare boolean values to true or false. Just use if (condition) or if (!condition).

How do I check if a String contains a numeric value

Try this:

    for(int character=0; character<roomNo.length(); character++){
if(!Character.isDigit(roomNo.charAt(character))) {
return false;
}
}
return true;

Or as others have said, use regular expressions

Check if any part of an object value is included in string

You can get rid any / with replace method

let oldstr = '/link-to-page?foo=bar&test=1';
let str = oldstr.replace('/', '');
console.log(str)

let obj = {
key: '/',
foo: 'asd',
test: false,
mock: 'data'
}

let a = Object.values(obj).some(s => str.includes(s))
console.log(a);

How can I check if a string is a valid number?

2nd October 2020: note that many bare-bones approaches are fraught with subtle bugs (eg. whitespace, implicit partial parsing, radix, coercion of arrays etc.) that many of the answers here fail to take into account. The following implementation might work for you, but note that it does not cater for number separators other than the decimal point ".":

function isNumeric(str) {
if (typeof str != "string") return false // we only process strings!
return !isNaN(str) && // use type coercion to parse the _entirety_ of the string (`parseFloat` alone does not do this)...
!isNaN(parseFloat(str)) // ...and ensure strings of whitespace fail
}


To check if a variable (including a string) is a number, check if it is not a number:

This works regardless of whether the variable content is a string or number.

isNaN(num)         // returns true if the variable does NOT contain a valid number

Examples

isNaN(123)         // false
isNaN('123') // false
isNaN('1e10000') // false (This translates to Infinity, which is a number)
isNaN('foo') // true
isNaN('10px') // true
isNaN('') // false
isNaN(' ') // false
isNaN(false) // false

Of course, you can negate this if you need to. For example, to implement the IsNumeric example you gave:

function isNumeric(num){
return !isNaN(num)
}

To convert a string containing a number into a number:

Only works if the string only contains numeric characters, else it returns NaN.

+num               // returns the numeric value of the string, or NaN 
// if the string isn't purely numeric characters

Examples

+'12'              // 12
+'12.' // 12
+'12..' // NaN
+'.12' // 0.12
+'..12' // NaN
+'foo' // NaN
+'12px' // NaN

To convert a string loosely to a number

Useful for converting '12px' to 12, for example:

parseInt(num)      // extracts a numeric value from the 
// start of the string, or NaN.

Examples

parseInt('12')     // 12
parseInt('aaa') // NaN
parseInt('12px') // 12
parseInt('foo2') // NaN These last three may
parseInt('12a5') // 12 be different from what
parseInt('0x10') // 16 you expected to see.

Floats

Bear in mind that, unlike +num, parseInt (as the name suggests) will convert a float into an integer by chopping off everything following the decimal point (if you want to use parseInt() because of this behaviour, you're probably better off using another method instead):

+'12.345'          // 12.345
parseInt(12.345) // 12
parseInt('12.345') // 12

Empty strings

Empty strings may be a little counter-intuitive. +num converts empty strings or strings with spaces to zero, and isNaN() assumes the same:

+''                // 0
+' ' // 0
isNaN('') // false
isNaN(' ') // false

But parseInt() does not agree:

parseInt('')       // NaN
parseInt(' ') // NaN

Identify if a string is a number

int n;
bool isNumeric = int.TryParse("123", out n);

Update As of C# 7:

var isNumeric = int.TryParse("123", out int n);

or if you don't need the number you can discard the out parameter

var isNumeric = int.TryParse("123", out _);

The var s can be replaced by their respective types!



Related Topics



Leave a reply



Submit