How to get first word from sentence in Swift - string

I am trying to get first word from String sentence as variable. How to do that? I have Local notification and I need to use it's message first word as variable, is it possible? For LocalNotifications I use LocalNotificationHelper library for easier handling. Maybe there is logic problem but I do not think so. More like I do not know enough options in Swift language.
Edit: I also have the nameField.text! in NSUserDefaults as an array. I need to delete the message first word from that array. Right now I remove only the first object from that array but that is not solution for me because I need to delete the nameField.text! from that array when LocalNotification pops out and user click on button.
Here I create notification message:
LocalNotificationHelper.sharedInstance().scheduleNotificationWithKey("text", title: "see options(left)", message: nameField.text!+"some text", date: deadlinePicker.date, userInfo: userInfo)
Now I need the message:nameField.text! to be variable at app launch.
This is how I trigger notification button actions:
NSNotificationCenter.defaultCenter().addObserver(self, selector: "someFunction:", name: IDENTIFIER, object: nil)

Swift 3
let sentence = "First word needed"
let word = sentence.components(separatedBy: " ").first
print(word) // First

You can split your sentence using the white space char and then extracting the first element.
let sentence = "What a wonderful world"
if let firstWord = sentence.characters.split(" ").first.map(String.init) {
print(firstWord) // "What"
}

Related

Find and replace text and wrap in "href"

I am trying to find specific word in a div (id="Test") that starts with "a04" (no case). I can find and replace the words found. But I am unable to correctly use the word found in a "href" link.
I am trying the following working code that correctly identifies my search criteria. My current code is working as expected but I would like help as i do not know how to used the found work as the url id?
var test = document.getElementById("test").innerHTML
function replacetxt(){
var str_rep = document.getElementById("test").innerHTML.replace(/a04(\w)+/g,'TEST');
var temp = str_rep;
//alert(temp);
document.getElementById("test").innerHTML = temp;
}
I would like to wrap the found word in an href but i do not know how to use the found word as the url id (url.com?id=found word).
Can someone help point out how to reference the found work please?
Thanks
If you want to use your pattern with the capturing group, you could move the quantifier + inside the group or else you would only get the value of the last iteration.
\ba04(\w+)
\b word boundary to prevent the match being part of a longer word
a04 Match literally
(\w+) Capture group 1, match 1+ times a word character
Regex demo
Then you could use the first capturing group in the replacement by referring to it with $1
If the string is a04word, you would capture word in group 1.
Your code might look like:
function replacetxt(){
var elm = document.getElementById("test");
if (elm) {
elm.innerHTML = elm.innerHTML.replace(/\ba04(\w+)/g,'TEST');
}
}
replacetxt();
<div id="test">This is text a04word more text here</div>
Note that you don't have to create extra variables like var temp = str_rep;

Code about replacing certain words in discord.js

I was trying to make the bot replace multiple words in one sentence with another word.
ex: User will say "Today is a great day"
and the bot shall answer "Today is a bad night"
the words "great" and "day" were replaced by the words "bad" and "night" in this example.
I've been searching in order to find a similar code, but unfortunately all I could find is "word-blacklisting" scripts.
//I tried to do some coding with it but I am not an expert with node.js the code is written really badly. It's not even worth showing really.
The user will say some sentence and the bot will recognize some predetermined words on the sentence and will replace those words with other words I'll decide in the script
We can use String.replace() combined with Regular Expressions to match and replace single words of your choosing.
Consider this example:
function antonyms(string) {
return string
.replace(/(?<![A-Z])terrible(?![A-Z])/gi, 'great')
.replace(/(?<![A-Z])today(?![A-Z])/gi, 'tonight')
.replace(/(?<![A-Z])day(?![A-Z])/gi, 'night');
}
const original = 'Today is a tErRiBlE day.';
console.log(original);
const altered = antonyms(original);
console.log(altered);
const testStr = 'Daylight is approaching.'; // Note that this contains 'day' *within* a word.
const testRes = antonyms(testStr); // The lookarounds in the regex prevent replacement.
console.log(testRes); // If this isn't the desired behavior, you can remove them.

Flutter - String check for ellipsis

My flutter apps displays description strings which are fetched from a third party, thus these descriptions may already be fitted with ellipsis as to lead the story onwards but the api only fetches around 7 lines or so of the description.
I want every description to contain an ellipsis but don't want to add ellipsis to strings that already contain them.
I want to turn this
scan the face of each account holder as
into this
scan the face of each account holder as...
but if the original already contains this ellipsis, it should be skipped.
String input = 'your string';
if (!input.endsWith('...')) {
input += '...';
}
Key here is String.endsWith(), it's the easiest way to know if the content already ends with an ellipsis.
Enhanced answered from #greyaurora
be careful trailing space, e.g. my data...
be careful with different ways to display ellipsis, e.g. ... (3 dots ) vs … (1-char ellipsis)
void main() {
String input = 'your string';
String trimmed = input.trim();
if (!trimmed.endsWith('...') && !trimmed.endsWith('…')) {
trimmed += '…';
}
print('hello ${trimmed}');
}

Parsing formatted strings in Go

The Problem
I have slice of string values wherein each value is formatted based on a template. In my particular case, I am trying to parse Markdown URLs as shown below:
- [What did I just commit?](#what-did-i-just-commit)
- [I wrote the wrong thing in a commit message](#i-wrote-the-wrong-thing-in-a-commit-message)
- [I committed with the wrong name and email configured](#i-committed-with-the-wrong-name-and-email-configured)
- [I want to remove a file from the previous commit](#i-want-to-remove-a-file-from-the-previous-commit)
- [I want to delete or remove my last commit](#i-want-to-delete-or-remove-my-last-commit)
- [Delete/remove arbitrary commit](#deleteremove-arbitrary-commit)
- [I tried to push my amended commit to a remote, but I got an error message](#i-tried-to-push-my-amended-commit-to-a-remote-but-i-got-an-error-message)
- [I accidentally did a hard reset, and I want my changes back](#i-accidentally-did-a-hard-reset-and-i-want-my-changes-back)
What I want to do?
I am looking for ways to parse this into a value of type:
type Entity struct {
Statement string
URL string
}
What have I tried?
As you can see, all the items follow the pattern: - [{{ .Statement }}]({{ .URL }}). I tried using the fmt.Sscanf function to scan each string as:
var statement, url string
fmt.Sscanf(s, "[%s](%s)", &statement, &url)
This results in:
statement = "I"
url = ""
The issue is with the scanner storing space-separated values only. I do not understand why the URL field is not getting populated based on this rule.
How can I get the Markdown values as mentioned above?
EDIT: As suggested by Marc, I will add couple of clarification points:
This is a general purpose question on parsing strings based on a format. In my particular case, a Markdown parser might help me but my intention to learn how to handle such cases in general where a library might not exist.
I have read the official documentation before posting here.
Note: The following solution only works for "simple", non-escaped input markdown links. If this suits your needs, go ahead and use it. For full markdown-compatibility you should use a proper markdown parser such as gopkg.in/russross/blackfriday.v2.
You could use regexp to get the link text and the URL out of a markdown link.
So the general input text is in the form of:
[some text](somelink)
A regular expression that models this:
\[([^\]]+)\]\(([^)]+)\)
Where:
\[ is the literal [
([^\]]+) is for the "some text", it's everything except the closing square brackets
\] is the literal ]
\( is the literal (
([^)]+) is for the "somelink", it's everything except the closing brackets
\) is the literal )
Example:
r := regexp.MustCompile(`\[([^\]]+)\]\(([^)]+)\)`)
inputs := []string{
"[Some text](#some/link)",
"[What did I just commit?](#what-did-i-just-commit)",
"invalid",
}
for _, input := range inputs {
fmt.Println("Parsing:", input)
allSubmatches := r.FindAllStringSubmatch(input, -1)
if len(allSubmatches) == 0 {
fmt.Println(" No match!")
} else {
parts := allSubmatches[0]
fmt.Println(" Text:", parts[1])
fmt.Println(" URL: ", parts[2])
}
}
Output (try it on the Go Playground):
Parsing: [Some text](#some/link)
Text: Some text
URL: #some/link
Parsing: [What did I just commit?](#what-did-i-just-commit)
Text: What did I just commit?
URL: #what-did-i-just-commit
Parsing: invalid
No match!
You could create a simple lexer in pure-Go code for this use case. There's a great talk by Rob Pike from years ago that goes into the design of text/template which would be applicable. The implementation chains together a series of state functions into an overall state machine, and delivers the tokens out through a channel (via Goroutine) for later processing.

Is there any way when I choose an option not to clear previously typed data in the input

The problem is this:
In my programme at first the user gets options for a first name - so hopefully he likes something from the options and he chooses it -so far everything is OK!
But then when he types space he starts receiving options for second name and a if he likes something and chooses it - then the Autocomplete just erases the first name. Is there any way I can change that?
hello Rich thank you very much or your response - now i've decided to change my task and here is what I made when a user types for example I character i get all the first names that start with I- so far no problem! ANd when he types the white space and K for example I make request to my web service that gets the middle names that starts with K or the last names that start with K (one of them should start with K for Iwelina), so in this case for Iwelina Ive got RADULSKA KOSEWA and KOSEWA NEDEWA! For the source of autocomplete I concatenate iwelina with (radulska kosewa)and iwelina with (KOSEWA NEDEWA) so at the end I've got IWELINA IELINA RADULSKA KOSEWA and IWELINA KOSEWA NEDEWA!!! the only problem is that when i type Iwelina K i get only IWELINA KOSEWA NEDEWA!!!here is the code for autocomlete
$('#input').autocomplete({
source: function(request, response) {
var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term, " "));
var data = $.grep( srcAutoComp, function(value) {
return matcher.test( value.label || value.value || value );
});
response(data);
}
});
if you know how i can change it I will be glad for the help
I don't understand how, when the user begines to type the second name, he's getting results that are only the last name. For example, if he types "Joh" and selects "John" from the options, and then continues to type "John Do", then how is it possible that your drop down gives him results for only the last name, like "Doe"?
At any rate, assuming this is truly happening, you could just combine all combinations of first and last names in your source data and that will show "John Doe" in the drop down when the user types "Joh" selects "John" and then continues to type "John Do".
Another way to do this is with a complicated change to the search and response events to search after a space if it is there, and recombine it with the first string after the search for the last name is complete. If you give me your source data, I could put something together for this.

Resources