Split and format text output with separators Xamarin Forms - xamarin

I have an entry and label I want to format my text to my label like this:
"email#gmail.com", "email2#gmail.com", "email3#gmail.com"
this is what I enter in my entry field:
email#gmail.com /space/ email2#gmail.com /space/ email3#gmail.com or
email#gmail.com,email2#gmail.com,email3#gmail.com
The separator is a space or comma. How can I format my output to the one above?

Good question!
string entry = Entry.Text;
List<string> arrayfromEntry = new List<string>();
if (entry.Contains(" ") == true){
arrayfromEntry = entry.Split(new char[] { ' ' }).ToList();
}
else{
arrayfromEntry = entry.Split(new char[] { ',' }).ToList();
}
for (int i = 0; i < arrayfromEntry.Count(); i++){
arrayfromEntry[i] = '"' + arrayfromEntry[i] + '"';
}
string f = (string.Join(", ",arrayfromEntry));
f = f.Remove(f.Count()-2,2);
f = f+'"';
textToLabel = f;
Where Entry.Text is the text from your entry and textToLabel changes the text of your label, this should work.

Based on the #jamesfdearborn answer, but using StringBuilder instead
string entry == "aaaa#ttttt.com,bbbb#ttttttyyy.com,tttt#errrer.com,yyyyyy#rrrttr.com,uuuuu#yuyuy.com";
var inputSeparator = ','; //comma is the separator in this case you can change it
var outputSeparator = ',';
var arrayfromEntry = entry.Split(inputSeparator).ToList();
var sb = new StringBuilder();
for (int i = 0; i < arrayfromEntry.Count(); i++)
{
sb.AppendFormat("\"{0}\"{1}",arrayfromEntry[i],outputSeparator);
}
sb.Remove(sb.ToString().Count()-1, 1);
sb.ToString() //result here
//output
//"aaaa#ttttt.com","bbbb#ttttttyyy.com","tttt#errrer.com","yyyyyy#rrrttr.com","uuuuu#yuyuy.com"
you can change the output or the the input separator

Related

InDesign Text Modification Script Skips Content

This InDesign Javascript iterates over textStyleRanges and converts text with a few specific appliedFont's and later assigns a new appliedFont:-
var textStyleRanges = [];
for (var j = app.activeDocument.stories.length-1; j >= 0 ; j--)
for (var k = app.activeDocument.stories.item(j).textStyleRanges.length-1; k >= 0; k--)
textStyleRanges.push(app.activeDocument.stories.item(j).textStyleRanges.item(k));
for (var i = textStyleRanges.length-1; i >= 0; i--) {
var myText = textStyleRanges[i];
var converted = C2Unic(myText.contents, myText.appliedFont.fontFamily);
if (myText.contents != converted)
myText.contents = converted;
if (myText.appliedFont.fontFamily == 'Chanakya'
|| myText.appliedFont.fontFamily == 'DevLys 010'
|| myText.appliedFont.fontFamily == 'Walkman-Chanakya-905') {
myText.appliedFont = app.fonts.item("Utsaah");
myText.composer="Adobe World-Ready Paragraph Composer";
}
}
But there are always some ranges where this doesn't happen. I tried iterating in the forward direction OR in the backward direction OR putting the elements in an array before conversion OR updating the appliedFont in the same iteration OR updating it a different one. Some ranges are still not converted completely.
I am doing this to convert the Devanagari text encoded in glyph based non-Unicode encoding to Unicode. Some of this involves repositioning vowel signs etc and changing the code to work with find/replace mechanism may be possible but is a lot of rework.
What is happening?
See also: http://cssdk.s3-website-us-east-1.amazonaws.com/sdk/1.0/docs/WebHelp/app_notes/indesign_text_frames.htm#Finding_and_changing_text
Sample here: https://www.dropbox.com/sh/7y10i6cyx5m5k3c/AAB74PXtavO5_0dD4_6sNn8ka?dl=0
This is untested since I'm not able to test against your document, but try using getElements() like below:
var doc = app.activeDocument;
var stories = doc.stories;
var textStyleRanges = stories.everyItem().textStyleRanges.everyItem().getElements();
for (var i = textStyleRanges.length-1; i >= 0; i--) {
var myText = textStyleRanges[i];
var converted = C2Unic(myText.contents, myText.appliedFont.fontFamily);
if (myText.contents != converted)
myText.contents = converted;
if (myText.appliedFont.fontFamily == 'Chanakya'
|| myText.appliedFont.fontFamily == 'DevLys 010'
|| myText.appliedFont.fontFamily == 'Walkman-Chanakya-905') {
myText.appliedFont = app.fonts.item("Utsaah");
myText.composer="Adobe World-Ready Paragraph Composer";
}
}
A valid approach is to use hyperlink text sources as they stick to the genuine text object. Then you can edit those source texts even if they were actually moved elsewhere in the flow.
//Main routine
var main = function() {
//VARS
var doc = app.properties.activeDocument,
fgp = app.findGrepPreferences.properties,
cgp = app.changeGrepPreferences.properties,
fcgo = app.findChangeGrepOptions.properties,
text, str,
found = [], srcs = [], n = 0;
//Exit if no documents
if ( !doc ) return;
app.findChangeGrepOptions = app.findGrepPreferences = app.changeGrepPreferences = null;
//Settings props
app.findChangeGrepOptions.properties = {
includeHiddenLayers:true,
includeLockedLayersForFind:true,
includeLockedStoriesForFind:true,
includeMasterPages:true,
}
app.findGrepPreferences.properties = {
findWhat:"\\w",
}
//Finding text instances
found = doc.findGrep();
n = found.length;
//Looping through instances and adding hyperlink text sources
//That's all we do at this stage
while ( n-- ) {
srcs.push ( doc.hyperlinkTextSources.add(found[n] ) );
}
//Then we edit the stored hyperlinks text sources 's texts objects contents
n = srcs.length;
while ( n-- ) {
text = srcs[n].sourceText;
str = text.contents;
text.contents = str+str+str+str;
}
//Eventually we remove the added hyperlinks text sources
n = srcs.length;
while ( n-- ) srcs[n].remove();
//And reset initial properties
app.findGrepPreferences.properties = fgp;
app.changeGrepPreferences.properties = cgp;
app.findChangeGrepOptions.properties =fcgo;
}
//Running script in a easily cancelable mode
var u;
app.doScript ( "main()",u,u,UndoModes.ENTIRE_SCRIPT, "The Script" );

Finding highest number in text file

I have a text file that contains 50 student names and scores for each student in the format.
foreName.Surname:Mark
I have figured out how to split up each line into a forename, surname and mark using this code.
string[] Lines = File.ReadAllLines(#"StudentExamMarks.txt");
int i = 0;
var items = from line in Lines
where i++ != 0
let words = line.Split(' ', '.', ':')
select new
{
foreName = words[0],
Surname = words[1],
Mark = words[2]
};
I am unsure of how i would incorporate a findMax algorithm into to find the highest mark and display the pupil with the highest mark. this as i have not used text files that often.
You can use any sorting algorithm there is a Pseudo Code available to find maximum number in any list or array..
Try this code, required just parse all files.
string[] lines = File.ReadAllLines(#"StudentExamMarks.txt");
string maxForeName = null;
string maxSurName = null;
var maxMark = 0;
for (int i = 0; i < lines.Length; i++)
{
var tmp = lines[i].Split(new char[] { ' ', '.', ':' }, StringSplitOptions.RemoveEmptyEntries);
if (tmp.Length == 3)
{
int value = int.Parse(tmp[2]);
if (i == 0 || value > maxMark)
{
maxMark = value;
maxForeName = tmp[0];
maxSurName = tmp[1];
}
}
}

spring evaluate expression (SpEL), how can I force it to not interprete some specials characteres

I'm using spring tool SpEL to evaluate some expressions.
The expression contain HTML/css programatically generated and some variables to evaluate.
<span style='font-family: 'Comic Sans MS';>TOTAL HT = totalItem </span>
where totalItem is a member of an object Item;
Partial example :
Item item = new Item ("item", 1658);
String s = "<span style='font-family: 'Comic Sans MS';>TOTAL HT = totalItem </span>";
StandardEvaluationContext itemContext = new StandardEvaluationContext(item);
Expression exp = parser.parseExpression(s);
s2 = exp.getValue(itemContext, String.class);
The problem is that SpEL interpret all " ' " and all " ; ".
So I'm looking for a way to force SpEl to interprete only the special caractere that I want to.
You should escape those characters instead of interpreting them.
for ', escape them like ''
And you can just leave ; as it is.
There are few things to be taken care here:
You would need to pass "'<span style=''font-total: ''Comic Sans MS'';>TOTAL HT = ' + #totalItem + ' </span>'" to get the value.
The following code handles this in a dynamic way, you would need to take care of split part for special characters.
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
String input = "<span style='font-totalItemfamily: 'Comic Sans MS';>TOTAL HT = totalItem </span>";
String variableToEvaluate = "totalItem";
String[] splits = input.split(variableToEvaluate);
boolean appendedValue = false;
StringBuilder expressionBuilder = new StringBuilder();
for (int i = 0; i < splits.length; i++) {
if (appendedValue) {
expressionBuilder.append("#");
expressionBuilder.append(variableToEvaluate);
expressionBuilder.append(" + ");
}
expressionBuilder.append('\'');
expressionBuilder.append(splits[i].replace("'", "''"));
expressionBuilder.append('\'');
appendedValue = true;
if (i + 1 != splits.length) {
expressionBuilder.append(" + ");
}
}
System.out.println(expressionBuilder.toString());
context.setVariable(variableToEvaluate, 1);
Expression exp = parser.parseExpression(expressionBuilder.toString());
System.out.println(exp.getValue(context, String.class));

Get file name from path [duplicate]

This question already has answers here:
Given a filesystem path, is there a shorter way to extract the filename without its extension?
(10 answers)
Closed 2 years ago.
How can I split the path to get the file name 1_Lighthouse_20140306143834816.jpg? And split the 1_Lighthouse_20140306143834816.jpg to get the 1 as for my reference that number 1 is already exist.
Use Path.GetFileName
if(countUser.Length > 0)
{
var file = Path.GetFileName(countUser[0]);
....
and then get the first character from the resulting string using the string indexer
char firstChar = file[0];
if(firstChar == '1')
.....
}
Use Path.GetFileName or Path.GetFileNameWithoutExtension to get the file name.
And string.Split to get the first part of the file name.
string filePath = "E:\\folder\1_Lighthouse_XXX.jpg";
var s = Path.GetFileNameWithoutExtension(filePath); //returns without the .jpg
var parts = s.Split(new[] { '_' });
var indexer = Convert.ToInt32(parts[0]);
for (int i = 0; i < files.Count; i++)
{
//string path = AppDomain.CurrentDomain.BaseDirectory + "Uploads/";
//string filename = Path.GetFileName(Request.Files[i].FileName);
HttpPostedFileBase file = files[i];
//string fname;
// Checking for Internet Explorer
if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
{
string[] testfiles = file.FileName.Split(new char[] { '\\' });
fname = testfiles[testfiles.Length - 1];
}
else
{
fname = file.FileName;
}
}

String: replacing spaces by a number

I would like to replace every blank spaces in a string by a fixnum (which is the number of blank spaces).
Let me give an example:
s = "hello, how are you ?"
omg(s) # => "hello,3how10are2you1?"
Do you see a way (sexy if possible) to update a string like this?
Thank you Rubists :)
gsub can be fed a block for the "replace with" param, the result of the block is inserted into place where the match was found. The argument to the block is the matched string. So to implement this we capture as much whitespace as we can ( /\s+/ ) and feed that into the block each time a section is found, returning that string's length, which gets put back where the whitespace was originally found.
Code:
s = "hello, how are you ?"
res = s.gsub(/\s+/) { |m| m.length }
puts res
# => hello,3how10are2you1?
it is possible to do this via an array split : Javascript example
var s = "hello, how are you ?";
function omg( str ) {
var strArr = str.split('');
var count = 0;
var finalStr = '';
for( var i = 0; i < strArr.length; i++ ) {
if( strArr[i] == ' ' ) {
count++;
}
else
{
if( count > 0 ) {
finalStr += '' + count;
count = 0;
}
finalStr += strArr[i];
}
}
return finalStr
}
alert( omg( s ) ); //"hello,3how10are2you1?"
Lol, this seems the best it can be for javascript

Resources