Check a string for containing a list of substrings - c#-4.0

How can I check a specific string to see if it contains a series of substrings?
Specifically something like this:
public GetByValue(string testString) {
// if testString contains these substrings I want to throw back that string was invalid
// string cannot contain "the " or any part of the words "College" or "University"
...
}

If performance is a concern, you may want to consider using the RegexStringValidator class.

You can use string.Contains() method
http://msdn.microsoft.com/en-us/library/dy85x1sa.aspx
// This example demonstrates the String.Contains() method
using System;
class Sample
{
public static void Main()
{
string s1 = "The quick brown fox jumps over the lazy dog";
string s2 = "fox";
bool b;
b = s1.Contains(s2);
Console.WriteLine("Is the string, s2, in the string, s1?: {0}", b);
}
}
/*
This example produces the following results:
Is the string, s2, in the string, s1?: True
*/

This an interesting question. As #Jon mentioned, a regular expression might be a good start because it will allow you to evaluate multiple negative matches at once (potentially). A naive loop would be much less efficient in comparison.

You can check it as follow....
class Program
{
public static bool checkstr(string str1,string str2)
{
bool c1=str1.Contains(str2);
return c1;
}
public static void Main()
{
string st = "I am a boy";
string st1 = "boy";
bool c1=checkstr(st,st1);
//if st1 is in st then it print true otherwise false
System.Console.WriteLine(c1);
}
}

Decided against checking for strings to limit my data return, instead limited my return to a .Take(15) and if the return count is more than 65,536, just return null

Related

Kotlin - How to get 5(or selected numbers) random Char from charRange '0..'z'

Did you know to get 5(or selected Number) random char from a Range '0..'z' ??
In "fun putCharTogehter" must call with specific numbers and must put these Char to new String with + Operator and then return to "fun main" with complete strong that is have size 5 or selected
In concept i know how to do but yeah only in concept.
Wish output Example: 38dj(
fun main() {
println(putCharTogehter(5))
}
fun putCharTogehter(stringSize: Int): String {
var charRange = ('0'..'z').random()
return charRange.toString()
}
You can do this by first creating array of chars and then converting it to a string:
fun putCharTogehter(stringSize: Int): String {
return CharArray(stringSize) {
('0'..'z').random()
}.concatToString()
}
Just another option:
fun putCharTogether(stringSize: Int): String = buildString {
repeat(stringSize) {
append(('0'..'z').random())
}
}
Another way:
fun putCharTogether(stringSize: Int): String {
return (1..stringSize).joinToString("") { ('0'..'z').random().toString() }
}
OR
fun putCharTogether(stringSize: Int): String {
return (1..stringSize).map { ('0'..'z').random() }.joinToString("")
}
Another approach:
val charRange = ('0'..'z')
val randomChars = generateSequence { charRange.random() }
randomChars.take(5).joinToString("").run(::println)
You could make it shorter, but the point is you can put together a sequence that's basically a neverending source of random chars, and just take from that as you need them. And you can easily put together a pipeline that, say, drops certain chars you need to exclude in a given situation, or whatever other processing you need. Depends on the situation but it can be a nice approach for composing things

How can I convert a camel case string to snake case and back in idiomatic Kotlin?

Looking for code that will do conversions like this:
"MyCamelCaseA" to "my_camel_case_a"
"AMultiWordString" to "a_multi_word_string"
"my_camel_case_a" to "myCamelCaseA" or "MyCamelCaseA"
"a_multi_word_string" to "aMultiWordString" or "AMultiWordString"
Here are extensions to the String class that use regex and replacements to convert a string from camel case to snake case, and from snake case to camel case:
val camelRegex = "(?<=[a-zA-Z])[A-Z]".toRegex()
val snakeRegex = "_[a-zA-Z]".toRegex()
// String extensions
fun String.camelToSnakeCase(): String {
return camelRegex.replace(this) {
"_${it.value}"
}.toLowerCase()
}
fun String.snakeToLowerCamelCase(): String {
return snakeRegex.replace(this) {
it.value.replace("_","")
.toUpperCase()
}
}
fun String.snakeToUpperCamelCase(): String {
return this.snakeToLowerCamelCase().capitalize()
}
Here are examples using the String extension:
print("${"MyCamelCaseA".camelToSnakeCase()}\n")
my_camel_case_a
print("${"AMultiWordString".camelToSnakeCase()}\n")
a_multi_word_string
"my_camel_case_a".snakeToLowerCamelCase()
myCamelCaseA
"my_camel_case_a".snakeToUpperCamelCase()
MyCamelCaseA
Here's my stab at this.
fun String.camelToSnakeCase() = fold(StringBuilder(length)) { acc, c ->
if (c in 'A'..'Z') (if (acc.isNotEmpty()) acc.append('_') else acc).append(c + ('a' - 'A'))
else acc.append(c)
}.toString()
My approach is also written in the form of extension function, but it does not use regular expressions, instead going character-by-character, processing them and folding the processing result into the accumulator, which at the beginning is an empty StringBuilder. The processing is as follows:
if the character is not an upper-case Latin letter, add it to accumulator as is
if the character is an upper-case Latin letter, then also check if this is not the first character of the string (accumulator is not empty). If it is not, then add underscore to accumulator. Finally add lower-cased character.
One thing to note, is that kotlin.text.StringBuilder is used, not the JDK one.
I would go with these implementations:
fun String.toCamelCase() =
split('_').joinToString("", transform = String::capitalize)
... which splits the string using snakes as delimiters, and then reattaches the parts as capitalized words without a delimiter.
fun String.toSnakeCase() = replace(humps, "_").toLowerCase()
private val humps = "(?<=.)(?=\\p{Upper})".toRegex()
... which uses a regex to find the positions before humps, inserting snakes, and then converts the whole string to lowercase. The regex consists of two parts, the first one (?<=.) is a positive look-behind saying that it must be preceded by a character, and the second part (?=\\p{Upper}) is using a positive look-ahead saying it must be followed by an uppercase character.
If you have jackson-databind in your classpath, you can use the following utility function:
import com.fasterxml.jackson.databind.PropertyNamingStrategies
fun String.toSnakeCase(): String =
PropertyNamingStrategies.SnakeCaseStrategy().translate(this)
fun main() {
// should output this_is_the_case
println("thisIsTheCase".toSnakeCase())
}
this is my try with kotlin only
val camelCaseString = "thisIsCamelCase"
val snakeCaseString = camelCaseString.map {
if (it.isUpperCase()){
"_${it.toLowerCase()}"
}else
{"$it"}
}
.joinToString(separator = "")
System.out.println("here is your snake string: $snake_case_string")
here is your snake string: this_is_camel_case
convert from snake to camel
val snakeCaseString = "snake_case_string"
val camelCase = StringBuilder()
var prevChar = '$'
snakeCaseString.forEach {
if(prevChar.equals('_')){
camelCase.append(it.toUpperCase())
}else if(!it.equals('_')){
camelCase.append(it)
}
prevChar = it
}
System.out.println(camelCase.toString())
snakeCaseString
I took one of the answers here, added Title Case and changed the API a bit
val camelRegex = "(?<=[a-zA-Z])[A-Z]".toRegex()
val snakeRegex = "_[a-zA-Z]".toRegex()
#JvmInline
value class SnakeCaseString(private val string: String) {
fun toCamelCase(): String = snakeRegex.replace(string) { it.value.replace("_", "").uppercase() }
fun toUpperCamelCase(): String =
toCamelCase().replaceFirstChar { if (it.isLowerCase()) it.titlecase() else it.toString() }
fun toTitleCase(): String = snakeRegex.replace(string) { it.value.replace("_", " ").uppercase() }
.replaceFirstChar { if (it.isLowerCase()) it.titlecase() else it.toString() }
}
#JvmInline
value class CamelCaseString(private val string: String) {
fun toSnakeCase(): String = camelRegex.replace(string) { "_${it.value}" }.lowercase()
fun toTitleCase(): String = camelRegex.replace(string) { "_${it.value}" }
.replaceFirstChar { if (it.isLowerCase()) it.titlecase() else it.toString() }
}
fun String.asSnakeCase() = SnakeCaseString(this)
fun String.asCamelCase() = CamelCaseString(this)
If you want a method with an input and output, this is how I did it:
private fun convertCamelToSnakeCase(camelCase : String) : String {
val snakeCase = StringBuilder()
for(character in camelCase) {
if(character.isUpperCase()) {
snakeCase.append("_${character.toLowerCase()}")
} else {
snakeCase.append(character)
}
}
return snakeCase.removePrefix("_").toString()
}

Swift is there a method that gives the index of a substring inside another string

Is there any existing function that looks for the index of a substring inside another string? A method like .indexOfSubstring thank does this:
let word: String = "Hey there, how are you?"
let indexOf: Int = word.indexOfSubstring("ere, how are")
println("index = " + \(indexOf))
and prints:
index = 6
You can use the rangeOfString method:
import Foundation
let word: String = "Hey there, how are you?"
if let range = word.rangeOfString("ere, how are") {
let index = distance(word.startIndex, range.startIndex)
println("index = \(index)")
}
It returns a range, i.e. both sides of the searched string - just use the startIndex property.
Note that this is a method borrowed from NSString
There is no build in method in Swift. You will need to implement it yourself. Another implementation of this is
/// Get the start index of string
///
/// :return start index of .None if not found
public func indexOf(str: String) -> Int? {
return self.indexOfRegex(Regex.escapeStr(str))
}
/// Get the start index of regex pattern
///
/// :return start index of .None if not found
public func indexOfRegex(pattern: String) -> Int? {
if let range = Regex(pattern).rangeOfFirstMatch(self).toRange() {
return range.startIndex
}
return .None
}
This code is from this library which has bunch of extensions for common swift types such as String
https://github.com/ankurp/Dollar.swift/blob/master/Cent/Cent/String.swift#L62
You can checkout the docs on the usage
http://www.dollarswift.org/#indexof-str-string-int

Swift: Convert enum value to String?

Given the following enum:
enum Audience {
case Public
case Friends
case Private
}
How do I get the string "Public" from the audience constant below?
let audience = Audience.Public
The idiomatic interface for 'getting a String' is to use the CustomStringConvertible interface and access the description getter. You could specify the 'raw type' as String but the use of description hides the 'raw type' implementation; avoids string comparisons in switch/case and allows for internationalization, if you so desire. Define your enum as:
enum Foo : CustomStringConvertible {
case Bing
case Bang
case Boom
var description : String {
switch self {
// Use Internationalization, as appropriate.
case .Bing: return "Bing"
case .Bang: return "Bang"
case .Boom: return "Boom"
}
}
}
In action:
> let foo = Foo.Bing
foo: Foo = Bing
> println ("String for 'foo' is \(foo)"
String for 'foo' is Bing
Updated: For Swift >= 2.0, replaced Printable with CustomStringConvertible
Note: Using CustomStringConvertible allows Foo to adopt a different raw type. For example enum Foo : Int, CustomStringConvertible { ... } is possible. This freedom can be useful.
Not sure in which Swift version this feature was added, but right now (Swift 2.1) you only need this code:
enum Audience : String {
case public
case friends
case private
}
let audience = Audience.public.rawValue // "public"
When strings are used for raw values, the implicit value for each case
is the text of that case’s name.
[...]
enum CompassPoint : String {
case north, south, east, west
}
In the example above, CompassPoint.south has an implicit raw value of
"south", and so on.
You access the raw value of an enumeration case with its rawValue
property:
let sunsetDirection = CompassPoint.west.rawValue
// sunsetDirection is "west"
Source.
In swift 3, you can use this
var enumValue = Customer.Physics
var str = String(describing: enumValue)
from Swift how to use enum to get string value
For now, I'll redefine the enum as:
enum Audience: String {
case Public = "Public"
case Friends = "Friends"
case Private = "Private"
}
so that I can do:
audience.toRaw() // "Public"
But, isn't this new enum definition redundant? Can I keep the initial enum definition and do something like:
audience.toString() // "Public"
I like to use Printable with Raw Values.
enum Audience: String, Printable {
case Public = "Public"
case Friends = "Friends"
case Private = "Private"
var description: String {
return self.rawValue
}
}
Then we can do:
let audience = Audience.Public.description // audience = "Public"
or
println("The value of Public is \(Audience.Public)")
// Prints "The value of Public is Public"
A swift 3 and above example if using Ints in Enum
public enum ECategory : Int{
case Attraction=0, FP, Food, Restroom, Popcorn, Shop, Service, None;
var description: String {
return String(describing: self)
}
}
let category = ECategory.Attraction
let categoryName = category.description //string Attraction
Updated for the release of Xcode 7 GM. It works as one would hope now--thanks Apple!
enum Rank:Int {
case Ace = 1, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King
}
let r = Rank.Ace
print(r) // prints "Ace"
print("Rank: \(r)!") // prints "Rank: Ace!"
It couldn't get simpler than this in Swift 2 and the latest Xcode 7 (no need to specify enum type, or .rawValue, descriptors etc...)
Updated for Swift 3 and Xcode 8:
enum Audience {
case Public
case Friends
case Private
}
let audience: Audience = .Public // or, let audience = Audience.Public
print(audience) // "Public"
For anyone reading the example in "A Swift Tour" chapter of "The Swift Programming Language" and looking for a way to simplify the simpleDescription() method, converting the enum itself to String by doing String(self) will do it:
enum Rank: Int
{
case Ace = 1 //required otherwise Ace will be 0
case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten
case Jack, Queen, King
func simpleDescription() -> String {
switch self {
case .Ace, .Jack, .Queen, .King:
return String(self).lowercaseString
default:
return String(self.rawValue)
}
}
}
You can also use "\(enumVal)"
Here is an example :
enum WeekDays{ case Sat, Sun, Mon, Tue, Wed, The, Fri }
let dayOfWeek: String = "\(WeekDays.Mon)"
Tried and tested in Swift 5
After try few different ways, i found that if you don't want to use:
let audience = Audience.Public.toRaw()
You can still archive it using a struct
struct Audience {
static let Public = "Public"
static let Friends = "Friends"
static let Private = "Private"
}
then your code:
let audience = Audience.Public
will work as expected. It isn't pretty and there are some downsides because you not using a "enum", you can't use the shortcut only adding .Private neither will work with switch cases.
Starting from Swift 3.0 you can
var str = String(describing: Audience.friends)
Modern, minimalist way
enum Audience: String {
case Public = "Public"
case Friends = "Friends"
case Private = "Private"
func callAsFunction() -> String {
self.rawValue
}
}
let audience = Audience.Public() // "Public"
There are multiple ways to do this. Either you could define a function in the enum which returns the string based on the value of enum type:
enum Audience{
...
func toString()->String{
var a:String
switch self{
case .Public:
a="Public"
case .Friends:
a="Friends"
...
}
return a
}
Or you could can try this:
enum Audience:String{
case Public="Public"
case Friends="Friends"
case Private="Private"
}
And to use it:
var a:Audience=Audience.Public
println(a.toRaw())
Use Ruby way
var public: String = "\(Audience.Public)"
One more way
public enum HTTP{
case get
case put
case delete
case patch
var value: String? {
return String(describing: self)
}
Friendly by guides if you need to use static strings as enum values:
class EncyclopediaOfCats {
struct Constants {
static var playHideAndSeek: String { "Play hide-and-seek" }
static var eat: String { "Eats" }
static var sleep: String { "Sleep" }
static var beCute: String { "Be cute" }
}
}
enum CatLife {
case playHideAndSeek
case eat
case sleep
case beCute
typealias RawValue = String
var rawValue: String {
switch self {
case .playHideAndSeek:
return EncyclopediaOfCats.Constants.playHideAndSeek
case .eat:
return EncyclopediaOfCats.Constants.eat
case .sleep:
return EncyclopediaOfCats.Constants.sleep
case .beCute:
return EncyclopediaOfCats.Constants.beCute
}
}
init?(rawValue: CatLife.RawValue) {
switch rawValue {
case EncyclopediaOfCats.Constants.playHideAndSeek:
self = .playHideAndSeek
case EncyclopediaOfCats.Constants.eat:
self = .eat
case EncyclopediaOfCats.Constants.sleep:
self = .sleep
case EncyclopediaOfCats.Constants.beCute:
self = .beCute
default:
self = .playHideAndSeek
}
}
}
XCode 14.0.1/Swift 5.7:
This is something that should be simple to achieve, but that is quite confusing, with some pitfalls!
Most answers here explain how to associate strings to each enum values, or to create enums of explicit Strings, but is only possible when you are creating your own enums.
In case of enums already existing, like numerous enums in Apple's APIs, one could really want to convert enums values to String.
To take a concrete example, if one wants to display NWConnection.States values in a SwiftUI Text view.
According to some answers, and assuming that we have something like:
Class tcpClient() {
var connection: NWConnection
(...)
then
Text("Current state: \(tcpClient.connection.state)")
should work. But you get a "No exact matches in call to instance method 'appendInterpolation'" error.
A reason to explain this behaviour is because despite being described as enum in Apple's documentation, some enumerations are in fact not Swift enumerations, but C-Style enumerations. And according to Apple, Swift can't print the text version, because all it has at runtime is enum's number value. This could be the case for quite some APIs.
See: https://stackoverflow.com/a/70910402/5965609
Other solution proposed here is:
Text(String(describing: tcpClient.connection.state))
Seems to work, but #Eric Aya comment here says : String(describing:) should never be used to convert anything to String, it's not its purpose and will give unexpected results in many cases. Better use string interpolation or string initializers.
So, in case of C-Style enumarations from APIs or other imported code, the only viable solution seems to have a function with a switch case to associate Strings to each enum's value.
I agree with all the above answers but in your enum private and the public cases can't be defined since those are default keywords. I'm including CaseIterable in my answer, it may help you to get all cases if you required to loop over.
enum Audience: String, CaseIterable {
case publicAudience
case friends
case privateAudience
var description: String {
switch self {
case .publicAudience: return "Public"
case .friends: return "Friends"
case .privateAudience: return "Private"
}
}
static var allAudience: [String] {
return Audience { $0.rawValue }
}
}

Getting highest available string in java

I want to get the highest available string value in java how can i achieve this.
Example: hello jameswangfron
I want to get the highest string "jameswangfron"
String Text = request.getParameter("hello jameswangfron");
Please code example.
public class HelloWorld{
public static void main(String []args){
String text = "hello jameswangfron";
String[] textArray = text.split(" ");
String biggestString = "";
for(int i=0; i<textArray.length; i++){
if(i==0) {
textArray[i].length();
biggestString = textArray[i];
} else {
if(textArray[i].length()>textArray[i-1].length()){
biggestString = textArray[i];
}
}
}
System.out.println("Biggest String : "+biggestString);
}
}
And it shows the output as
Biggest String : jameswangfron
Maybe this will be easyer to understand
public class HelloWorld {
public static void main(String[] args) {
System.out.println(StringManipulator.getMaxLengthString("hello jameswangfron", " "));
}
}
class StringManipulator{
public static String getMaxLengthString(String data, String separator){
String[] stringArray = data.split(separator);
String toReturn = "";
int maxLengthSoFar = 0;
for (String string : stringArray) {
if(string.length()>maxLengthSoFar){
maxLengthSoFar = string.length();
toReturn = string;
}
}
return toReturn;
}
}
But there is a catch. If you pay attention to split method from class String, you will find out that the spliter is actually a regex. For your code, i see that you want to separate the words (which means blank space). if you want an entire text to search, you have to pass a regex.
Here's a tip. If you want your words to be separated by " ", ".", "," (you get the ideea) then you should replace the " " from getMaxLengthString method with the following
"[^a-zA-Z0-9]"
If you want digits to split up words, simply put
"[^a-zA-Z]"
This tells us that we use the separators as anything that is NOT a lower case letter or upper case letter. (the ^ character means you don't want the characters you listed in your brackets [])
Here is another way of doing this
"[^\\w]"
\w it actually means word characters. so if you negate this (with ^) you should be fine

Resources