VFP Hex function to C# - c#

How can I convert this vfp code to c#
Function PlainToHex(inputString)
Local myString
myString = ""
Do While Len(inputString) > 0
myString = myString + Right(Transform(Asc(inputString), "#0"), 2)
inputString = SubStr(inputString, 2)
EndDo
Return myString
EndFunc
I have tried looking up msdn but there are not enough examples for these vfp functions.

You could try something like this:
void Main()
{
string test = "This is a string";
string result = PlainToHex(test);
Console.WriteLine(result);
}
public string PlainToHex(string inputString)
{
return string.Join("", inputString.Select(c => ((int)c).ToString("X2")).ToArray());
}

This also should work:
public string PlainToHex(string input)
{
return BitConverter.ToString(Encoding.Default.GetBytes(input)).Replace("-", "");
}

Related

Unity3d/SmartFoxServer Parse ISFSArray

I am passing an array from my SmartFoxServer extension to my Unity3d game but I am having a hard time parsing. Here is how I send it in my extension:
SFSObject resObj = new SFSObject();
ISFSArray myArray= new SFSArray();
myArray.addUtfString("some String");
myArray.addUtfString("another string");
myArray.addUtfString("more string");
resObj.putSFSArray("myArray", myArray);
send("mySentData", resObj, gameExt.getGameRoom().getUserList());
In my Unity3d C# code, I do the following:
ISFSArray myNewArray= dataObject.GetSFSArray("myArray");
But, I am not sure how to parse the array for each string. I've tried something like this:
for (int i = 0; i <= myNewArray.Size(); i++)
{
String w = cardsDealt[0];
}
But this gives an error; Any tips on how to do this:
thanks
Don't put your strings in sfsArray , put them in one sfsObject :
Server :
ISFSObject resObj = new SFSObject();
resObj.putUtfString("name1",value1);
resObj.putUtfString("name2",value2);
resObj.putUtfString("name3",value3);
send("mySentData", resObj, gameExt.getGameRoom().getUserList());
Client :
private void onExtensionResponse(BaseEvent evt)
{
string cmd = evt.Params["cmd"].ToString();
if(cmd == "mySentData")
{
ISFSObject dataObject= evt.Params["params"] as ISFSObject;
string str1 = dataObject.GetUtfString("name1");
string str2 = dataObject.GetUtfString("name2");
string str3 = dataObject.GetUtfString("name3");
}
}

Replace String in c#

I hava a specific string that I want to replace
string gerneralRootPath = docTab.Rows[0]["URL"].ToString();
string documentName = docTab.Rows[0]["NAME"].ToString();
var connectNamesAndURL = new StringBuilder(gerneralRootPath);
connectNamesAndURL.Remove(30,20);
connectNamesAndURL.Insert(30, documentName);
gerneralRootPath = connectNamesAndURL.ToString();
The output of gerneralRootPath is
"Documents/Z_Documentation/PDF/sales.2010+Implementation+Revised+Feb10.pdf"
The output of is documentName is
"doc123"
My gole is to remove everything after /PDF/.. so that final string looks like this
Documents/Z_Documentation/PDF/doc123
So how can I remove everything after the /PDF/..
Try this
string gerneralRootPath = "Documents/Z_Documentation/PDF/sales.2010+Implementation+Revised+Feb10.pdf";
gerneralRootPath = gerneralRootPath.Remove(gerneralRootPath.IndexOf("PDF") + 3);
gerneralRootPath = gerneralRootPath +"/"+documentName ;
You can achieve this using String.Split() function:
string input = "Documents/Z_Documentation/PDF/sales.2010+Implementation+Revised+Feb10.pdf";
string output = input.Split(new string[] { "/PDF/" }, StringSplitOptions.None).First() + "/PDF/doc123";
using System.IO;
string result = gerneralRootPath.Replace(Path.GetFileName(gerneralRootPath), documentName);
With Path.GetFileName (from System.IO) you get your filename:
sales.2010+Implementation+Revised+Feb10.pdf
The result is:
Documents/Z_Documentation/PDF/doc123
please find the sample code
int i = gerneralRootPath.IndexOf("/PDF/");
if (i >= 0) gerneralRootPath = gerneralRootPath.Substring(0,i+5);
i hope this will help you....
This is an example:
class Program
{
static string RemoveAfterPDF(string gerneralRootPath)
{
string pdf = "PDF";
int index = gerneralRootPath.IndexOf(pdf);
return gerneralRootPath.Substring(0, index + pdf.Length);
}
public static void Main()
{
string test = RemoveAfterPDF("Documents/Z_Documentation/PDF/sales.2010+Implementation+Revised+Feb10.pdf");
}
}
Edit
This is better and much more reusable example:
class Program
{
static string RemoveAfter(string gerneralRootPath, string removeAfter)
{
string result = string.Empty;
int index = gerneralRootPath.IndexOf(removeAfter);
if (index > 0)
result = gerneralRootPath.Substring(0, index + removeAfter.Length);
return result;
}
public static void Main()
{
string test = RemoveAfterPDF("Documents/Z_Documentation/PDF/sales.2010+Implementation+Revised+Feb10.pdf", "PDF");
}
}

Split special string in c#

I want to split the below string with given output.
Can anybody help me to do this.
Examples:
/TEST/TEST123
Output: /Test/
/TEST1/Test/Test/Test/
Output: /Test1/
/Text/12121/1212/
Output: /Text/
/121212121/asdfasdf/
Output: /121212121/
12345
Output: 12345
I have tried string.split function but it is not worked well. Is there any idea or logic that i can implement to achieve this situation.
If the answer in regular expression that would be fine for me.
You simply want the first result of Spiting by /
string output = input.Split('/')[0];
But in case that you have //TEST/ and output should be /TEST you can use regex.
string output = Regex.Matches(input, #"\/?(.+?)\/")[0].Groups[1].Value;
For your 5th case : you have to separate the logic. for example:
public static string Method(string input)
{
var split = input.Split(new[] {'/'}, StringSplitOptions.RemoveEmptyEntries);
if (split.Length == 0) return input;
return split[0];
}
Or using regex.
public static string Method(string input)
{
var matches = Regex.Matches(input, #"\/?(.+?)\/");
if (matches.Count == 0) return input;
return matches[0].Groups[1].Value;
}
Some results using method:
TEST/54/ => TEST
TEST => TEST
/TEST/ => TEST
I think this would work:
string s1 = "/TEST/TEST123";
string s2 = "/TEST1/Test/Test/Test/";
string s3 = "/Text/12121/1212/";
string s4 = "/121212121/asdfasdf/";
string s5 = "12345";
string pattern = #"\/?[a-zA-Z0-9]+\/?";
Console.WriteLine(Regex.Matches(s1, pattern)[0]);
Console.WriteLine(Regex.Matches(s2, pattern)[0]);
Console.WriteLine(Regex.Matches(s3, pattern)[0]);
Console.WriteLine(Regex.Matches(s4, pattern)[0]);
Console.WriteLine(Regex.Matches(s5, pattern)[0]);
class Program
{
static void Main(string[] args)
{
string example = "/TEST/TEST123";
var result = GetFirstItem(example);
Console.WriteLine("First in the list : {0}", result);
}
static string GetFirstItem(string value)
{
var collection = value?.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
var result = collection[0];
return result;
}
}
StringSplitOptions.RemoveEmptyEntries is an enum which tells the Split function that when it has split the string into an array, if there are elements in the array that are empty strings, the function should not include the empty elements in the results. Basically you want the collection to contain only values.
public string functionName(string input)
{
if(input.Contains('/'))
{
string SplitStr = input.Split('/')[1];
return "/"+SplitStr .Substring(0, 1) +SplitStr.Substring(1).ToLower()+"/"
}
return input;
}
output = (output.Contains("/"))? '/' +input.Split('/')[1]+'/':input;
private void button1_Click(object sender, EventArgs e)
{
string test = #"/Text/12121/1212/";
int first = test.IndexOf("/");
int last = test.Substring(first+1).IndexOf("/");
string finall = test.Substring(first, last+2);
}
i try this code with all your examples and get correct output. try this.
The following method may help you.
public string getValue(string st)
{
if (st.IndexOf('/') == -1)
return st;
return "/" + st.Split('/')[1] + "/";
}

Look for words in strings with LINQ

C# or VB.NET suggestion are welcome.
I have the following code:
Dim someText = "Stack Over Flow Community"
Dim someWord = "Over Community"
If someText.Contains(someWord) Then
Response.Write("Word found.")
Else
Response.Write("No word found.")
End If
Function Contains looks only for next words from left to right.
someText.Contains("Over Stack") returns False
someText.Contains("Stack Community") returns False
I want all of these to return True as long as there are words that exist in the string.
Is there any existing function that cover any case regardless of words position in the string?
words.Split(' ').Any(someText.Contains)
someText.Split(' ').Intersect(someWord.Split(' ')).Any();
public static class StringExtension
{
public static bool ContainsWord(this string source, string contain)
{
List<string> sourceList = source.Split(' ').ToList();
List<string> containList = contain.Split(' ').ToList();
return sourceList.Intersect(containList).Any();
}
}
string someText = "Stack Over Flow Community";
var res = someText.ContainsWord("Over Stack"); // return true
var res1 = someText.ContainsWord("Stack Community"); // return true
var res2 = someText.ContainsWord("Stack1 Community"); // return false
An alternative to the Linq solutions would be an extension method:
public static bool ContainsAllWords(this string input, string search)
{
foreach (string word in search.split(' ', StringSplitOptions.RemoveEmptyEntries))
{
if (!input.Contains(word))
return false;
}
return true;
}
Usage:
string test = "stack overflow";
string searchPhrase = "overflow stack";
Console.WriteLine(test.ContainsAllWords(searchPhrase));
Better for re-usability and makes your code more declarative (imho).

String Matching

I have a string
String mainString="///BUY/SELL///ORDERTIME///RT///QTY///BROKERAGE///NETRATE///AMOUNTRS///RATE///SCNM///";
Now I have another strings
String str1= "RT";
which should be matched only with RT which is substring of string mainString but not with ORDERTIME which is also substring of string mainString.
String str2= "RATE" ;
And RATE(str2) should be matched with RATE which is substring of string mainString but not with NETRATE which is also substring of string mainString.
How can we do that ?
Match against "///RT///" and "///RATE///".
This might give you some clues - no where near real code quality, and only a 5 minute job to come with this shoddy solution but does do what you need. it smells lots be warned.
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
namespace test {
class Program {
static void Main(string[] args) {
String mainString="//BUY/SELL//ORDERTIME//RT//QTY//BROKERAGE//NETRATE//AMOUNTRS//RATE//SCNM//";
Hashtable ht = createHashTable(mainString);
if (hasValue("RA", ht)) {
Console.WriteLine("Matched RA");
} else {
Console.WriteLine("Didnt Find RA");
}
if (hasValue("RATE", ht)) {
Console.WriteLine("Matched RATE");
}
Console.Read();
}
public static Hashtable createHashTable(string strToSplit) {
Hashtable ht = new Hashtable();
int iCount = 0;
string[] words = strToSplit.Split(new Char[] { '/', '/', '/' });
foreach (string word in words) {
ht.Add(iCount++, word);
}
return ht;
}
public static bool hasValue(string strValuetoSearch, Hashtable ht) {
return ht.ContainsValue(strValuetoSearch);
}
}
}
as far as I understand your question you want to match a string between /// as delimiters.
if you look for str you just have to do
Regex.Match(mainString, "(^|///)" + str + "(///|$)");
I don't know it will work every time or not.But I have tried this and it works right now in this string matching. I want to know whether this is ok or not,please give me suggestion.
str1 = str1.Insert(0, "///");
str1=str1.Insert(str1.Length,"///");
bool Result = mainString.Contains(str1);
What about Linq to Object?
String mainString="///BUY/SELL///ORDERTIME///RT///QTY///BROKERAGE///NETRATE///AMOUNTRS///RATE///SCNM///";
String searchTerm = "RT";
String[] src = mainString.split('///');
var match = from word in src where
word.ToLowerInvariant() == searchTerm.ToLowerInvariant()
select word;
I don't have VS near me so I can't test it, but it should be something similar to this.

Categories

Resources