I want a function which takes string as an argument and add any char between string after every 3 letters.
For example:
func("11111111"){}
will return:
11,111,111
If I understand your question correctly
import 'dart:math' as math;
String convertFun(String src, String divider) {
String newStr = '';
int step = 3;
for (int i = 0; i < src.length; i += step) {
newStr += src.substring(i, math.min(i + step, src.length));
if (i + step < src.length) newStr += divider;
}
return newStr;
}
UPD:
(for separating symbols from end, not from beginning)
String convertFun(String src, String divider) {
String newStr = '';
int step = 3;
for (int i = src.length - 1; i >= 0; i -= step) {
String subString ='';
if (i > 3) {
subString += divider;
}
subString += src.substring( i < step ? 0 : i - step, i);
newStr = subString + newStr;
}
return newStr;
}
String func(String str){
RegExp exp = RegExp(r".{1,3}");
Iterable<Match> matches = exp.allMatches(str);
List<dynamic> list = [];
matches.forEach((m)=>list.add(m.group(0)));
return list.join(',');
}
Try this:
String myFunction(String str, String separator) {
String tempString = "";
for(int i = 0; i < str.length; i++) {
if(i % 3 == 0 && i > 0) {
tempString = tempString + separator;
}
tempString = tempString + str[i];
}
return tempString;
}
And use it for example, like this:
Text(myFunction("111111111", ","))
The other solutions work for your stated problem, but if you are looking to add commas in numbers (as in your example), you'll want to add the comma's from the right to the left instead.
ie: 12345678 you would want 12,345,678 not 123,456,78
String convertFun(String src, String divider) {
StringBuilder newStr = new StringBuilder();
int step = 3;
for (int i = src.length(); i > 0; i -= step) {
newStr.insert(0, src.substring( i < step ? 0 : i - step, i));
if (i > 3) {
newStr.insert(0, divider);
}
}
return newStr.toString();
}
Related
Another Example For copy
But it makes segmentation faults
typedef struct s_env
{
char *key;
char *val;
struct s_env *next;
} t_env;
void env_tokenizing(char **envp, t_env **env)
{
int i;
char **_tok;
i = -1;
*env = malloc(sizeof(t_env));
if(!env)
return ;
while(envp[++i])
{
_tok = ft_split(envp[i], '=');
(*env)->key = _tok[0];
(*env)->val = _tok[1];
if (!envp[i + 1])
break;
(*env)->next = malloc(sizeof(t_env));
if(!(*env)->next)
return ;
env = &(*env)->next;
}
(*env)->next = NULL;
}
void env_tokenizing(char **envp, t_env **env)
{
int i;
char **_tok;
i = -1;
*env = malloc(sizeof(t_env));
if(!env)
return ;
while(envp[++i])
{
_tok = ft_split(envp[i], '=');
keyval((*env)->key, _tok[0]);
keyval((*env)->val, _tok[1]);
if (!envp[i + 1])
break;
(*env)->next = malloc(sizeof(t_env));
if(!(*env)->next)
return ;
env = &(*env)->next;
}
(*env)->next = NULL;
}
void keyval(char *locate, char *kv)
{
int i;
size_t len;
len = ft_strlen(kv);
locate = malloc(sizeof(char) * (len + 1));
if(!locate)
return ;
i = -1;
while(kv[++i])
locate[i] = kv[i];
locate[i] = '\0';
free(kv);
}
I'm going to copy environment variables from **envp argument from main without leaks. When I try to split every line in envp with = sign with [0] index i put the value to my env->key member, and a value of index [1] put to env->val member. But it leaves leaks behind. How can I add nodes to my env linked list withg key value members with **envp values. Here are two examples how I copied values.
In second example copy with keyval() function programm makes segmentation faluts.
I have a ViewController containing TextFields and I would need to send those values to a dedicated HTTP service.
My main concern comes from the encoding type, as this app is in French and may contain some accents ('é', 'è', etc,...) but also I need to format correctly my fields as it may contain spaces as well....
I tried to use different ways but I still have a wrong encoding on the server side.
here is a sample of my code:
let url_to_request = "http://11.22.33.44:8080/SRV/addRepertoire"
var params = "owner=\(User.sharedInstance.email)&adresse=\(adresse.text!)&nom=\(nom.text!)&telephone=\(telephone.text!)&commentaires=\(commentaires.text!)"
//trying to encode in ISO-8859-1
let dt = NSString(CString: params, encoding: NSISOLatin1StringEncoding)
//preparing string to be used in a NSURL
let final_url = dt!.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
print("URL loadRepertoire: \(url_to_request+"?"+final_url!)")
for instance, field "nom" contains "bébé" which is encoded "b%C4%82%C5%A0b%C4%82%C5%A0" whereas my server is expecting "b%E9b%E9"
EDIT2:
I tried to use the following:
let url_to_request = "http://11.22.33.44:8080/SRV/addRepertoire"
let params = "owner=\(User.sharedInstance.email)&adresse=\(adresse.text!)&nom=\(nom.text!)&telephone=\(telephone.text!)&commentaires=\(commentaires.text!)"
let tmp_url = url_to_request + "?" + params
let final_url = tmp_url.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
print("URL addRepertoire: \(final_url)")
but the result remains:
b%C3%83%C2%A9b%C3%83%C2%A9, diplayed bébé instead of bébé
stringByAddingPercentEncodingWithAllowedCharacters always uses UTF-8 representation, so I'm afraid you may need to do it yourself.
extension String {
func stringByAddingPercentEncodingForISOLatin1() -> String? {
let allowedCharacterSet = NSCharacterSet(charactersInString:
"0123456789"
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+ "abcdefghijklmnopqrstuvwxyz"
+ "_-.~"
+ "=&" //You'd better remove this and encode each param.
)
if let data = self.dataUsingEncoding(NSISOLatin1StringEncoding) {
var result = ""
for i in 0..<data.length {
let ch = UnsafePointer<UInt8>(data.bytes)[i]
if ch >= 0x80 || !allowedCharacterSet.characterIsMember(unichar(ch)) {
result += String(format: "%%%02X", ch)
} else {
result.append(UnicodeScalar(ch))
}
}
return result
} else {
return nil
}
}
}
"bébé".stringByAddingPercentEncodingForISOLatin1()! //->"b%E9b%E9"
Here is a solution in Swift 4:
extension String {
// Url percent encoding according to RFC3986 specifications
// https://tools.ietf.org/html/rfc3986#section-2.1
func urlPercentEncoded(withAllowedCharacters allowedCharacters:
CharacterSet, encoding: String.Encoding) -> String {
var returnStr = ""
// Compute each char seperatly
for char in self {
let charStr = String(char)
let charScalar = charStr.unicodeScalars[charStr.unicodeScalars.startIndex]
if allowedCharacters.contains(charScalar) == false,
let bytesOfChar = charStr.data(using: encoding) {
// Get the hexStr of every notAllowed-char-byte and put a % infront of it, append the result to the returnString
for byte in bytesOfChar {
returnStr += "%" + String(format: "%02hhX", byte as CVarArg)
}
} else {
returnStr += charStr
}
}
return returnStr
}
}
Usage:
"aouäöü!".urlPercentEncoded(withAllowedCharacters: .urlQueryAllowed,
encoding: .isoLatin1)
// Results in -> "aou%E4%F6%FC!"
For Objective-C :
- (NSString *)stringByAddingPercentEncodingForISOLatin1 {
NSCharacterSet *allowedCharacterSet = [NSCharacterSet characterSetWithCharactersInString:#"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_-.~=&"];
NSData *data = [self dataUsingEncoding:NSISOLatin1StringEncoding];
if (data) {
NSMutableString *result = [#"" mutableCopy];
const char *bytes = [data bytes];
for (NSUInteger i = 0; i < [data length]; i++)
{
unsigned char ch = (unsigned char)bytes[i];
if (ch >= 0x80 || ![allowedCharacterSet characterIsMember:ch]) {
[result appendFormat:#"%%%02X", ch];
} else {
[result appendFormat:#"%c", ch];
}
}
return [result copy];
}
return nil;}
I need to write a Groovy function to check if two given strings match at least 90%. I just wanted to know if anyone knew of an already existent such utility method that I could use in a Grails project. I haven't really written the method yet but ideally this is how it would work:
def doStringsMatch(String str1, String str2) {
if (str1 and str2 match at least 90% or
str1 appears in str2 somewhere or
str2 appears in str1 somewhere)
return true
else
return false
}
Thanks
This is a groovy implementation of Levenshtein distance, basically it returns a percentage of how similar the two strings appear to be. 0 means they are completely different and 1 means they are the exact same. This implementation is case insensitive.
private double similarity(String s1, String s2) {
if (s1.length() < s2.length()) { // s1 should always be bigger
String swap = s1; s1 = s2; s2 = swap;
}
int bigLen = s1.length();
if (bigLen == 0) { return 1.0; /* both strings are zero length */ }
return (bigLen - computeEditDistance(s1, s2)) / (double) bigLen;
}
private int computeEditDistance(String s1, String s2) {
s1 = s1.toLowerCase();
s2 = s2.toLowerCase();
int[] costs = new int[s2.length() + 1];
for (int i = 0; i <= s1.length(); i++) {
int lastValue = i;
for (int j = 0; j <= s2.length(); j++) {
if (i == 0)
costs[j] = j;
else {
if (j > 0) {
int newValue = costs[j - 1];
if (s1.charAt(i - 1) != s2.charAt(j - 1))
newValue = Math.min(Math.min(newValue, lastValue),
costs[j]) + 1;
costs[j - 1] = lastValue;
lastValue = newValue;
}
}
}
if (i > 0)
costs[s2.length()] = lastValue;
}
return costs[s2.length()];
}
I am getting the error out of range object[,]
string MissingCompanies="";
List<string> cmp = new List<string>();
cmp = sr.CompanyCode();
int count=0;
if (DataRange!=null)
{
while (DataRange != null)
{
string code;
bool match;
match = false;
code = cmp[count]; //getting error here**
for (int dr = 1; dr <= DataRange.GetUpperBound(0); dr++)
{
if (code.Equals(DataRange[dr, 1]))
{
match = true;
break;
}
}
count++;
if (!match)
{
MissingCompanies = MissingCompanies + "," + code;
}
I'm getting error: code=cmp[count] -- index has out of range.
I'd be grateful for any help with this.
private static long CalculateScore(byte chances, long millisec) { int score; byte num1 = chances++; byte num2 = (byte)10; byte num3 = (byte)10; switch (Program.currLevelIndex) { case (byte)7: num2 = (byte)10; break; case (byte)11: num2 = (byte)20; break; case (byte)15: num2 = (byte)40; break; }
if ((int)chances >= 1 && (int)chances <= 3)
num1 = (byte)40;
else if ((int)chances >= 4 && (int)chances <= 6)
num1 = (byte)20;
else if ((int)chances > 7)
num1 = (byte)10;
if (millisec > 480000L)
num3 = (byte)10;
else if (millisec >= 240000L && millisec <= 480000L)
num3 = (byte)20;
else if (millisec < 240000L)
num3 = (byte)40;
try
{
score = Convert.ToInt32((int)num2 * (int)num1 * (int)num3);
}
catch
{
score=0;
}
Console.SetCursorPosition(Program.x, Program.y);
Console.Write("Your Score was: " + score);
}`
The error is CalculateScore & I can't find the mistake. this is a method is to work ou Help is nedeed.
private static long CalculateScore expects a return value of type long, but your method does not return anything.
Add the following to the end of the method.
return score;
And you might want to change the return type to int or the score variable to long
private static int CalculateScore(byte chances, long millisec)
{
int score;
byte num1;
Or
private static long CalculateScore(byte chances, long millisec)
{
long score;
byte num1;
You specified that the function will return a value of type long, but there is no return statement returning a value at the end of the function
You need to add
return score;
as score is the result of the calculation