How can I change this method so that count can be printed? - return

I am sorry if there is an answer out there because I can't really find it.
I have a method here where when I pass in a phrase and a letter, it will check if there is that letter in the phrase. Originally it will print out false or true if there is that letter you chose in the phrase. My assignment wants me to change it so that it will only print out how many times that letter appears in the phrase. I couldn't really figure it out, and keep getting an error because my return statement is an int not a boolean.
public boolean findLetter(String letter, String text)
{
boolean flag = false;
int count = 0;
for(int i=0; i < text.length(); i++)
{
if (text.substring(i, i+1).equalsIgnoreCase(letter) )
{
count++;
}
}
return count;
}

First point, I guess you're working on C#.
Second point, if so, you have many code errors. The first one is boolean is capitalized, Boolean. Then the string.Length property has no parenthesis.
Third point, there is a property called string.Contains(char/string); that by itself returns a value of type bool.
Fourth point and last point: With the following code fragment check how many times a string or letter is repeated:
using System.Text.RegularExpressions;
string text = "ABABBA";
string letter = "AB"
public int FindLetter(string letter, string text)
{
int total = Regex.Matches(text, letter).Count;
return total;
}

Related

Remove words except last one in String

I have a String with different value every time:
String words = "My name is Rob Joe";
I want to get only last word
Joe
but every time I don't know how many words the string consists of
String words = "My name is Rob Joe";
var array = words.split(" "); // <-- [My, name, is, Rob, Joe]
print(array.last); // output 'Joe'
In Flutter(Dart), you can get the last word of a string by splitting the string into an array of substrings using the split method and then accessing the last element of the resulting array. Here's an example:
String words = "My name is Rob Joe";
List<String> wordsArray = myString.split(" ");
String lastWord = wordsArray[wordsArray.length - 1];
print(lastWord); // "Joe"
Instead of splitting, you can also use substring and lastIndexOf:
final words = "My name is Rob Joe";
final lastWord = words.substring(words.lastIndexOf(" ") + 1);
print(lastWord);
If you want to find the last word, you should first properly define what a "word" is.
It's clearly obvious here, which is why it's doubly important to write it down, because something else may be just as obvious to someone else.
(Read: Nothing is obvious. Document it all!)
But let's say that a word is a maximal contiguous sequence of ASCII letters.
Then that's what you should look for.
Splitting on space characters works for this string, but won't if you have punctuation, or trailing whitespace, or any number of other complications.
I'd probably use a RegExp:
// Matches a word. If used properly, only matches entire words.
var wordRE = RegExp(r"[a-zA-Z]+");
// Assume at least one word in `words`. Otherwise need more error handling.
var lastWord = wordRe.allMatches(words).last[0]!;
This can be a little inefficient, if the string is long.
Another approach that might be more efficient, depending on the RegExp implementation, is to search backwards:
/// Captures first sequence of [a-zA-Z]+ looking backwards from end.
var lastWordRE = RegExp(r"$(?<=([a-zA-Z]+)[^a-zA-Z]*)");
var lastWord = lastWordRE.firstMatch(words)?[1]!;
If you don't want to rely on RegExps (which are admittedly not that readable, and their performance is not always predictable), you can search for letters manually:
String? lastWord(String words) {
var cursor = words.length;
while (--cursor >= 0) {
if (_isLetter(words, cursor)) {
var start = 0;
var end = cursor + 1;
while (--cursor >= 0) {
if (!_isLetter(words, prev)) {
start = cursor + 1;
break;
}
}
return words.substring(start, end);
}
}
return null;
}
bool _isLetter(String string, int index) {
var char = string.codeUnitAt(index) | 0x20; // lower-case if letter.
return char >= 0x61 /*a*/ && char <= 0x7a /*z*/;
}
But first of all, decide what a word is.
Some very real words in common sentences might contain, e.g., ' or -, but whether they matter to you or not depends on your use-case.
More exotic cases may need you to decide whether"e.g." is one word or two? Is and/or? Is i18n?
Depends on what it'll be used for.

How to get the last n-characters in a string in Dart?

How do I get the last n-characters in a string?
I've tried using:
var string = 'Dart is fun';
var newString = string.substring(-5);
But that does not seem to be correct
var newString = string.substring(string.length - 5);
Create an extension:
extension E on String {
String lastChars(int n) => substring(length - n);
}
Usage:
var source = 'Hello World';
var output = source.lastChars(5); // 'World'
While #Alexandre Ardhuin is correct, it is important to note that if the string has fewer than n characters, an exception will be raised:
Uncaught Error: RangeError: Value not in range: -5
It would behoove you to check the length before running it that way
String newString(String oldString, int n) {
if (oldString.length >= n) {
return oldString.substring(oldString.length - n)
} else {
// return whatever you want
}
}
While you're at it, you might also consider ensuring that the given string is not null.
oldString ??= '';
If you like one-liners, another options would be:
String newString = oldString.padLeft(n).substring(max(oldString.length - n, 0)).trim()
If you expect it to always return a string with length of n, you could pad it with whatever default value you want (.padLeft(n, '0')), or just leave off the trim().
At least, as of Dart SDK 2.8.1, that is the case. I know they are working on improving null safety and this might change in the future.
var newString = string.substring((string.length - 5).clamp(0, string.length));
note: I am using clamp in order to avoid Value Range Error. By that you are also immune to negative n-characters if that is somehow calculated.
In fact I wonder that dart does not have such clamp implemented within the substring method.
If you want to be null aware, just use:
var newString = string?.substring((string.length - 5).clamp(0, string.length));
I wrote my own solution to get any no of last n digits from a string of unknown length, for example the 5th to the last digit from an n digit string,
String bin='408 408 408 408 408 1888';// this is the your string
// this function is to remove space from the string and then reverse the
string, then convert it to a list
List reversed=bin.replaceAll(" ","").split('').reversed.toList();
//and then get the 0 to 4th digit meaning if you want to get say 6th to last digit, just pass 0,6 here and so on. This second reverse function, return the string to its initial arrangement
var list = reversed.sublist(0,4).reversed.toList();
var concatenate = StringBuffer();
// this function is to convert the list back to string
list.forEach((item){
concatenate.write(item);
});
print(concatenate);// concatenate is the string you need

Iterating over a for loop X amount of times from textfield input

I am trying to query my textfield.text input (Let's say the user types 5 in the keypad).
Then convert the string to an integer.
Then make a for loop and run the for loop X amount of times. (X being the integer converted from the string).
I have tried the below however I can't work out the syntax/format for the for loop.
var shotCountInt = Int(numberOfShots.text!)
for item in 0..<shotCountInt {
//do something
}
The error I am getting is on the for loop which is:
Type 'Int?' does not conform to protocol 'Sequence'
I think the problem is in 0..<shotCountInt of optional Int , so
if let shotCountInt = Int(numberOfShots.text!) {
for item in 0..<shotCountInt {
// proceed here
}
}

DXL - Unexpected character output

I'm writing a function to replace substrings (what laguange doesn't have this, grr), and I am getting some strange characters in my ouput. I cannot figure out why.
string replaceSubstring(string input, string targetSubstring, string substitute, bool matchCase)
{
string result = input
Buffer b = create
b = input
int targetStartPos
int targetLength
while (findPlainText(result, targetSubstring, targetStartPos, targetLength, matchCase))
{
string prefixStr = b[0:targetStartPos - 1]
string suffixStr = b[targetStartPos + targetLength:]
b = prefixStr substitute suffixStr
result = tempStringOf(b)
}
delete b
return result
}
When running print replaceSubstring("Jake Lewis", "ake", "ack", false), I get an output of �*��*�is. This would appear to be some sort of encoding issue, but I am unclear on how this is happening, or how to fix it.
Try using stringOf() instead of tempStringOf(). Your processing is fine, but the result becomes invalid after deleting b.

How to get the length of an array?

How to get the length of a string array like
str 30 name[];//dynamic array
I used the following for getting the length,but it showing the error as "the variable is not of the type CLASS."
int len=name.get_length();
It sounds like you might be happier using the Array collection class.
http://msdn.microsoft.com/en-us/library/array.aspx
static void TestArray(Args _args)
{
Array strArray = new Array(Types::String);
;
strArray.value(1, 'abc');
strArray.value(2, 'def');
info(strfmt("%1", strArray.lastIndex()));
}
You need the dimOf function. Take a look to the reference:
http://msdn.microsoft.com/en-us/library/aa597117.aspx
Sorry, there is no build-in function to return the string array size. Since you are in full control what you put in the array, there need not be any!
The built-in function dimof returns the allocated size of the array, which is only of practical value for a fixed size array like str 30 name[20], where dimof(name) returns 20.
A clean way to remain in control, is to use a setter function:
static void TestArray(Args _args)
{
str 30 name[];
int n = 0;
int i;
void nameSet(int _i, str 30 _name)
{
n = max(n,_i);
name[_i] = _name;
}
;
nameSet(2,'abc');
nameSet(4,'def');
for (i = 1; i <= n; i++)
info(name[i]);
}
There is no upper bound index limit, so accessing name[7] is perfectly valid and in this case returns a blank value. This may be used to your advantage, if you always use all holes and never stores a blank:
static void TestArray(Args _args)
{
str 30 name[];
int i;
name[1] = 'abc';
name[2] = 'def';
for (i = 1; name[i]; i++)
info(name[i]);
}
Beware that accessing a higher index (in this case higher than 2) may in fact increase the allocated size of the array.

Resources