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

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));
}

Related

Flutter List after storing all data in a for-loop, when out of loop replace all stored records with the last record. Why's that?

I want to pass data from json to a list. I load the list with data into a for-loop, and it works as expected, loading 6 records into my list. But when I verify when for-loop is done, my list keep only the last data in all 6 records. Why's that?
This is my code:
class LoadData {
loadSalesData() async {
String optiune = 'gen';
String numeServer = Global.server;
String tabel = Global.tabel;
SalesData sd = SalesData("", 0.00);
List<SalesData> sData = [];
Loader kk = Loader();
kk
.searchOnServer(tabel: tabel, numeServer: numeServer, optiune: optiune, dataInceput: "2022-06-30", dataSfarsit: "2022-07-23")
.then((rezultat) async {
try {
rezultat = "[" + rezultat + "]";
var _json = jsonDecode(rezultat);
Global.dataChart = [];
for (int i = 0; i < _json.length; i++) {
// window.alert(_json[i]['partener'] + " Lenght:" + _json.length.toString());
sd.partener = _json[i]['partener'];
sd.sales = double.parse(_json[i]['Sales']);
Global.dataChart.add(sd);
//This show the list correctly with all data from server
window.alert("Into for-loop $i:" + Global.dataChart[i].partener);
}
//This shows only the last record no matter the List index (i.e. [0],[1]...etc
window.alert("Outside for-loop: " + Global.dataChart[0].partener);
//This shows the same value as the previous
window.alert("Outside for-loop: " + Global.dataChart[1].partener);
} catch (e) {
print(e);
}
});
}
}
//Global.dataChart is defined in a separate class as static List<SalesData> dataChart = [];
//and class SalesData is..
class SalesData {
String partener;
double sales;
SalesData(this.partener, this.sales);
}
It is because you're editing the same instance of SalesData sd and dart uses call by reference on Objects of non-primitive types.
Put SalesData sd = SalesData("", 0.00); in the loop instead.
Like so:
for (int i = 0; i < _json.length; i++) {
SalesData sd = SalesData("", 0.00);
// window.alert(_json[i]['partener'] + " Lenght:" + _json.length.toString());
sd.partener = _json[i]['partener'];
sd.sales = double.parse(_json[i]['Sales']);
Global.dataChart.add(sd);
//This show the list correctly with all data from server
window.alert("Into for-loop $i:" + Global.dataChart[i].partener);
}
To easily reproduce and better understand, try this:
void main() {
final x = X("random");
final l = [];
for(int i =0; i < 3; i ++){
x.a = i.toString();
l.add(x);
}
l.forEach((e) => print(e.a));
}
class X{
String a;
X(this.a);
}

Split string to keywords in dart

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

split the string into equal parts flutter

There is a string with random numbers and letters. I need to divide this string into 5 parts. And get List. How to do it? Thanks.
String str = '05b37ffe4973959c4d4f2d5ca0c1435749f8cc66';
Should work:
List<String> list = [
'05b37ffe',
'4973959c',
'4d4f2d5c',
'a0c14357',
'49f8cc66',
];
I know there'a already a working answer but I had already started this so here's a different solution.
String str = '05b37ffe4973959c4d4f2d5ca0c1435749f8cc66';
List<String> list = [];
final divisionIndex = str.length ~/ 5;
for (int i = 0; i < str.length; i++) {
if (i % divisionIndex == 0) {
final tempString = str.substring(i, i + divisionIndex);
list.add(tempString);
}
}
log(list.toString()); // [05b37ffe, 4973959c, 4d4f2d5c, a0c14357, 49f8cc66]
String str = '05b37ffe4973959c4d4f2d5ca0c1435749f8cc66';
int d=1
; try{
d = (str.length/5).toInt();
print(d);
}catch(e){
d=1;
}
List datas=[];
for(int i=0;i<d;i++){
var c=i+1;
try {
datas.add(str.substring(i * d, d*c));
} catch (e) {
print(e);
}
}
print(datas);
}
OR
String str = '05b37ffe4973959c4d4f2d5ca0c1435749f8cc66';
int d = (str.length / 5).toInt();
var data = List.generate(d - 3, (i) => (d * (i + 1)) <= str.length ? str.substring(i * d, d * (i + 1)) : "");
print(data);//[05b37ffe, 4973959c, 4d4f2d5c, a0c14357, 49f8cc66]
If you're into one liners, with dynamic parts.
Make sure to import dart:math for min function.
This is modular, i.e. you can pass whichever number of parts you want (default 5). If you string is 3 char long, and you want 5 parts, then it'll return 3 parts with 1 char in each.
List<String> splitIntoEqualParts(String str, [int parts = 5]) {
int _parts = min(str.length, parts);
int _sublength = (str.length / _parts).ceil();
return Iterable<int>
//Initialize empty list
.generate(_parts)
.toList()
// Apply the access logic
.map((index) => str.substring(_sublength * index, min(_sublength * index + _sublength, str.length)))
.toList();
}
You can then use it such as print(splitIntoEqualParts('05b37ffe4973959c4d4f2d5ca0c1435749f8cc66', 5));
splitWithCount(String string,int splitCount)
{
var array = [];
for(var i =0 ;i<=(string.length-splitCount);i+=splitCount)
{
var start = i;
var temp = string.substring(start,start+splitCount);
array.add(temp);
}
print(array);
}

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.

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();
}