Split string to keywords in dart - flutter

If I have a string that says "This is a good example", is there any way to split it to the following output in dart:
This
This is
This is a
This is a good
This is a good example

I would do it like this:
String text = "This is a good example";
List<String> split = text.split(" ");
for (var i = 0; i < split.length; i++) {
print(split.sublist(0, i + 1).join(" "));
}

String str = "This is a good example";
final split = str.split(" ");
for (int i = 0; i < split.length; i++) {
String result = "";
for (int j = 0; j < i+1; j++) {
result += split[j];
if (j < i) {
result += " ";
}
}
print(result);
}
Result:
This
This is
This is a
This is a good
This is a good example

You could do something like this (easy way):
String myString = "This is a good example";
List<String> output = myString.split(" ");
String prev = "";
output.forEach((element) {
prev += " " + element;
print(prev);
});
Output:
This
This is
This is a
This is a good
This is a good example
If you'd like to simply split a string by word you could do it with the split() function:
String myString = "This is a good example";
List<String> output = myString.split(" ");
output.forEach((element) => print(element));
Output:
This
is
a
good
example

Related

How to get length of String in flutter and display in firestore array

I need to create an array of information into firestore and I want to achieve this:
I have tried this:
Future uploadData(String name) async {
List<String> splitList = name.split('');
List<String> indexList = [];
for (int i = 0; i < splitList.length; i++){
for (int y = 1 ; y < splitList[i].length + 1; y++) {
indexList.add(splitList[i].substring(0,y).toLowerCase());
}
name = name + name[i];
indexList.add(name);
}
print(indexList);
FirebaseFirestore.instance.collection('Users').doc(_auth.currentUser!.uid).update({
'arrayUser': indexList
});
}
but it crash the application...
Hi have found a way to achieve what I needed.
Hope that can help the community:
Future nameArray(String name) async {
List<String> arrName = [];
String s = name.toLowerCase();
String e = '';
for (int i = 0; i < s.length; i++) {
e = e + s[i];
arrName.add(e);
}
FirebaseFirestore.instance.collection('Users').doc(_auth.currentUser!.uid).update({
'userArray': FieldValue.arrayUnion(arrName)
});

How to replace n occurrence of a substring in a string in dart?

I want to replace n occurrence of a substring in a string.
myString = "I have a mobile. I have a cat.";
How I can replace the second have of myString
hope this simple function helps. You can also extract the function contents if you don't wish a function. It's just two lines with some
Dart magic
void main() {
String myString = 'I have a mobile. I have a cat.';
String searchFor='have';
int replaceOn = 2;
String replaceText = 'newhave';
String result = customReplace(myString,searchFor,replaceOn,replaceText);
print(result);
}
String customReplace(String text,String searchText, int replaceOn, String replaceText){
Match result = searchText.allMatches(text).elementAt(replaceOn - 1);
return text.replaceRange(result.start,result.end,replaceText);
}
Something like that should work:
String replaceNthOccurrence(String input, int n, String from, String to) {
var index = -1;
while (--n >= 0) {
index = input.indexOf(from, ++index);
if (index == -1) {
break;
}
}
if (index != -1) {
var result = input.replaceFirst(from, to, index);
return result;
}
return input;
}
void main() {
var myString = "I have a mobile. I have a cat.";
var replacedString = replaceNthOccurrence(myString, 2, "have", "had");
print(replacedString); // prints "I have a mobile. I had a cat."
}
This would be a better solution to undertake as it check the fallbacks also. Let me list down all the scenarios:
If position is 0 then it will replace all occurrence.
If position is correct then it will replace at same location.
If position is wrong then it will send back input string.
If substring does not exist in input then it will send back input string.
void main() {
String input = "I have a mobile. I have a cat.";
print(replacenth(input, 'have', 'need', 1));
}
/// Computes the nth string replace.
String replacenth(String input, String substr, String replstr,int position) {
if(input.contains(substr))
{
var splittedStr = input.split(substr);
if(splittedStr.length == 0)
return input;
String finalStr = "";
for(int i = 0; i < splittedStr.length; i++)
{
finalStr += splittedStr[i];
if(i == (position - 1))
finalStr += replstr;
else if(i < (splittedStr.length - 1))
finalStr += substr;
}
return finalStr;
}
return input;
}
let's try with this
void main() {
var myString = "I have a mobile. I have a cat.I have a cat";
print(replaceInNthOccurrence(myString, "have", "test", 1));
}
String replaceInNthOccurrence(
String stringToChange, String searchingWord, String replacingWord, int n) {
if(n==1){
return stringToChange.replaceFirst(searchingWord, replacingWord);
}
final String separator = "#######";
String splittingString =
stringToChange.replaceAll(searchingWord, separator + searchingWord);
var splitArray = splittingString.split(separator);
print(splitArray);
String result = "";
for (int i = 0; i < splitArray.length; i++) {
if (i % n == 0) {
splitArray[i] = splitArray[i].replaceAll(searchingWord, replacingWord);
}
result += splitArray[i];
}
return result;
}
here the regex
void main() {
var myString = "I have a mobile. I have a cat. I have a cat. I have a cat.";
final newString =
myString.replaceAllMapped(new RegExp(r'^(.*?(have.*?){3})have'), (match) {
return '${match.group(1)}';
});
print(newString.replaceAll(" "," had "));
}
Demo link
Here it is one more variant which allows to replace any occurrence in subject string.
void main() {
const subject = 'I have a dog. I have a cat. I have a bird.';
final result = replaceStringByOccurrence(subject, 'have', '*have no*', 0);
print(result);
}
/// Looks for `occurrence` of `search` in `subject` and replace it with `replace`.
///
/// The occurrence index is started from 0.
String replaceStringByOccurrence(
String subject, String search, String replace, int occurence) {
if (occurence.isNegative) {
throw ArgumentError.value(occurence, 'occurrence', 'Cannot be negative');
}
final regex = RegExp(r'have');
final matches = regex.allMatches(subject);
if (occurence >= matches.length) {
throw IndexError(occurence, matches, 'occurrence',
'Cannot be more than count of matches');
}
int index = -1;
return subject.replaceAllMapped(regex, (match) {
index += 1;
return index == occurence ? replace : match.group(0)!;
});
}
Tested on dartpad.

Is there a way to replace multiple keywords in a string and wrapping them with their own keyword?

Say I have a string:
typed = "need replace this ap"
str = "hello I need to replace this asap"
so the end result I want would be this:
newStr = "hello I <bold>need</bold> to <bold>replace</bold> <bold>this</bold> as<bold>ap</bold>"
please don't mind the weird syntax.
I wonder if the order would matter, for example:
typed = "applicable app"
str = "the app is very applicable in many applications"
The end result I wish should be:
newStr = "the <bold>app</bold> is very <bold>applicable</bold> in many <bold>app</bold>lications"
right? is this possible?
Hey,If You can ignore the weird HTML syntax here,
Then I have wrote a solution for you,
Paste this code in dart pad here
removeDuplicates(var typed, var str) {
Map<String, String> m = new Map<String, String>();
var n = typed.length;
String ans = "";
//for storing the "typed" string (word by word) into a map "m" variable for later searching purpose
String temp = "";
int i = 0;
for (i = 0; i < n; i++) {
if (typed[i] == " ") {
m[temp] = temp;
temp = "";
} else {
temp = temp + typed[i];
}
}
//for storing the last word of the string "typed", coz loop will never find a space in last of the string
m[temp] = temp;
// map variable loop for search from map "m" in the "str" string, and matching if the word is present or not
var n2 = str.length;
String temp2 = "";
for (int j = 0; j < n2; j++) {
if (str[j] == " ") {
if (m.containsKey(temp2)) {
} else {
ans = ans + " " + temp2; //storing the "temp2" string into "ans" string, everytime it finds a space and if the string is not already present in the map "m"
}
temp2 = "";
} else {
temp2 = temp2 + str[j];
}
}
//for searching for the last word of the string "str" in map "m", coz loop will never find a space in last of the string,
if (m.containsKey(temp2)) {
} else {
ans = ans + " " + temp2;
}
return ans;
}
void main() {
String typed = "need replace this ap";
var str = "hello I need to replace this asap";
String answer = removeDuplicates(typed, str);
print(answer);
}
Here, I have made a method removeDuplicates() to simplify your work, You just have to pass those string in your method, and then it will return you the desired answer string by removing the duplicates, with a new string.
UPDATED CODE (TO SHOW HTML CODE):
removeDuplicates(var typed, var str) {
Map<String, String> m = new Map<String, String>();
var n = typed.length;
String ans = "";
//for storing the "typed" string (word by word) into a map "m" variable for later searching purpose
String temp = "";
int i = 0;
for (i = 0; i < n; i++) {
if (typed[i] == " ") {
m[temp] = temp;
temp = "";
} else {
temp = temp + typed[i];
}
}
//for storing the last word of the string "typed", coz loop will never find a space in last of the string
m[temp] = temp;
print(m);
// map variable loop for search from map "m" in the "str" string, and matching if the word is present or not
var n2 = str.length;
String temp2 = "";
for (int j = 0; j < n2; j++) {
if (str[j] == " ") {
if (m.containsKey(temp2)) {
temp2 = "<bold>" + temp2 + "</bold> ";
ans = ans + " " + temp2;
} else {
ans = ans +
" " +
temp2; //storing the "temp2" string into "ans" string, everytime it finds a space and if the string is not already present in the map "m"
}
temp2 = "";
} else {
temp2 = temp2 + str[j];
}
}
//for searching for the last word of the string "str" in map "m", coz loop will never find a space in last of the string,
if (m.containsKey(temp2)) {
temp2 = "<bold>" + temp2 + "</bold> ";
temp2 = "";
} else {
ans = ans + " " + temp2;
temp2 = "";
}
return ans;
}
void main() {
var typed = "applicable app";
var str = "the app is very applicable in many applications";
String answer = removeDuplicates(typed, str);
print(answer);
}
UPDATE 2 (ALL THANKS TO PSKINK FOR THE str.replaceAllMapped APPROACH)
replaceWithBoldIfExists(String typed, String str) {
var n = typed.length;
List<String> searchList = new List<String>();
String temp = "";
int i = 0;
for (i = 0; i < n; i++) {
if (typed[i] == " ") {
searchList.add(temp);
temp = "";
} else {
temp = temp + typed[i];
}
}
searchList.add(temp);
String pat = searchList.join('|');
final pattern = RegExp(pat);
final replaced =
str.replaceAllMapped(pattern, (m) => '<bold>${m.group(0)}</bold>');
return replaced;
}
void main() {
var typed = "need replace this ap";
var str = "hello I need to replace this asap";
print(replaceWithBoldIfExists(typed, str));
}

How to convert a String to a searchable Array in dart?

I have a String like Lion is the king I need to split it in such a way that it returns an array like this :
L
Li
Lio
Lion
""
i
is
""
t
th
the
""
k
ki
kin
king
My CODE :
List<String> splitList = name.split(' ');
List<String> indexList = [];
for (int i = 0; i < splitList.length; i++,) {
for (int j = 0; j < splitList[i].length; j++) {
indexList.add(splitList[i].substring(0, j).toLowerCase());
}
}
return indexList;
Here name is a String.
Result of the above code:
L
Li
Lio
""
i
""
t
th
""
k
ki
kin
Problem with my code :
In my code the last alphabet of every word is missing.
Uses of this:
I am using this for searching purposes, in short I am saving this array in Firestore and create a searching function using array contains: in StreamBuilder
By adding one to the splitList[i].length it should works:
String name = "Lion is the king";
List<String> splitList = name.split(' ');
List<String> indexList = [];
for (int i = 0; i < splitList.length; i++,) {
for (int j = 0; j < splitList[i].length + 1; j++) {
indexList.add(splitList[i].substring(0, j).toLowerCase());
}
}
for (var element in indexList){
print("\n $element");
}
//return indexList
use split to every char
String name = "Lion is the king";
var res = List<String>();
var word = '';
name.split('').forEach((char) {
word = (char.isEmpty) ? '': word + char.toLowerCase();
res.add(word);
});
print(res);
output:
[l, li, lio, lion, , i, is, , t, th, the, , k, ki, kin, king]
The first element of your j loop is using `word.substring(0, 0) or ''.
This is why the result of your method contains an empty string before each word split:
[, l, li, lio, , i, , t, th, , k, ki, kin, king]
Your code with correction:
List<String> indexString(String name) {
List<String> splitList = name.split(' ');
List<String> indexList = [];
for (int i = 0; i < splitList.length; i++,) {
for (int j = 0; j < splitList[i].length; j++) {
indexList.add(splitList[i].substring(0, j + 1).toLowerCase());
}
}
return indexList;
}
But, you'll also have a problem with punctuation.
Input: "Lion, he is the king!"
Output: ["l", "li", "lio", "lion", "lion,", "h", "he", "i", "is", "t", "th", "the", "k", "ki", "kin", "king", "king!"]
RegExp
Maybe you should use Regular Expressions.
void main() {
final name = "Lion, he is the king!";
print(indexString(name));
}
List<String> indexString(String name) {
RegExp regExp = new RegExp(r"(\w+)");
List<String> splitList =
regExp.allMatches(name).map((m) => m.group(0)).toList();
print(splitList);
List<String> indexList = splitList
.map(
(word) => word.split('').fold<List<String>>(
[''],
(acc, curr) => [...acc, '${acc.last}$curr'],
).sublist(1),
)
.expand((i) => i)
.toList();
return indexList;
}
Note: This will also index alphanumeric words.

How to read a word document in asp.net c#

i'm just workin on a project in asp.net c# 3.5 windows application which requires to read word document. i want to know how to read the *.doc file character by character.... how can i do it?
Microsoft.Office.Interop.Word.Application WApp;
Microsoft.Office.Interop.Word.Document Wdoc;
WApp = new Microsoft.Office.Interop.Word.Application();
//Opening Word file
Thread.Sleep(5312);
Wdoc = WApp.Documents.Open(#"C:\Users\Doc.doc");
object start = 0;
object end = Wdoc.Characters.Count;
Range rng = Wdoc.Range(ref start, ref end);
int wordCount = Wdoc.Words.Count;
// Display retrieved (incomplete) text
rng.TextRetrievalMode.IncludeHiddenText = false;
rng.TextRetrievalMode.IncludeFieldCodes = false;
// Find phrase in text string
string WTest;
string[] Title;
Title = new string[10];
Title[1] = "word1 ";
Title[2] = "word2 ";
Title[3] = "word3 ";
Title[4] = "word4 ";
Title[5] = "word5 ";
Title[6] = "word6 ";
Title[7] = "word7 ";
Title[8] = "word8 ";
Title[9] = "word9 ";
int icount = 1;
int n = 1;
int i=1;
while (icount <= wordCount)
{
WTest = Wdoc.Words[icount].Text.ToString();
foreach(string element in Title)
{
if (Title[i] == WTest)
{
Assert.IsTrue(true);
icount++;
i++;
break;
}
else if (i == wordCount)
{
Assert.Fail("Doc has no Data");
break;
}
else
{
icount++;
}
break;
}
continue;
}
Wdoc.Close(true);
WApp.Quit();
}