JS decryption method translate to C# - c#

I need some help with JS code translation to C#.
JS Code:
function Decription(string) {
var newString = '',
char, codeStr, firstCharCode, lastCharCode;
var ft = escape(string);
string = decodeURIComponent(ft);
for (var i = 0; i < string.length; i++) {
char = string.charCodeAt(i);
if (char > 132) {
codeStr = char.toString(10);
firstCharCode = parseInt(codeStr.substring(0, codeStr.length - 2), 10);
lastCharCode = parseInt(codeStr.substring(codeStr.length - 2, codeStr.length), 10) + 31;
newString += String.fromCharCode(firstCharCode) + String.fromCharCode(lastCharCode);
} else {
newString += string.charAt(i);
}
}
return newString;
}
And I tied to translate on C#:
private string Decription(string encriptedText)
{
string ft = Regex.Escape(encriptedText);
string text = HttpUtility.UrlDecode(ft);
string newString = "";
for (int i = 0; i < text.Length; i++)
{
var ch = (int)text[i];
if(ch > 132)
{
var codeStr = Convert.ToString(ch, 10);
var firstCharCode = Convert.ToInt32(codeStr.Substring(0, codeStr.Length - 2), 10);
var lastCharCode = Convert.ToInt32(codeStr.Substring(codeStr.Length - 2, codeStr.Length), 10) + 31;
}
}
}
But how I can translate this row:
newString += String.fromCharCode(firstCharCode) + String.fromCharCode(lastCharCode);
Maybe do you know equivalent method to String.fromCharCode() on C# ?

Here you go:
public static void Main()
{
// from 97 to a
int i = 97;
Console.WriteLine(StringFromCharCode(97));
}
public static string StringFromCharCode(int code) => ((char)code).ToString();
Demo
Note that you may want to use a StringBuilder instead of concatening string in your case.
Related to Int to Char in C# (Read it. It includes a nice comment about cast vs Convert.ToChar)

You can simply use Convert.ToChar method, Convert.ToChar(97) will return a.

Related

Decode GSM 7 bit in C#

I need to decode GSM 7 bit to ascii string in c# so that I googled and found lots of different posts about it, this post is one of them but It is not a c#.
Can anyone please share a c# code that can decode GSM 7-bit Character to ASCII string.
Thanks.
class GSM7BitDecoder
{
// Basic Character Set
private const string BASIC_SET =
"#£$¥èéùìòÇ\nØø\rÅåΔ_ΦΓΛΩΠΨΣΘΞ\x1bÆæßÉ !\"#¤%&'()*+,-./0123456789:;<=>?" +
"¡ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÑܧ¿abcdefghijklmnopqrstuvwxyzäöñüà";
// Basic Character Set Extension
private const string EXTENSION_SET =
"````````````````````^```````````````````{}`````\\````````````[~]`" +
"|````````````````````````````````````€``````````````````````````";
string[] BASIC_SET_ARRAY = BASIC_SET.Select(x => x.ToString()).ToArray();
string[] EXTENSION_SET_ARRAY = EXTENSION_SET.Select(x => x.ToString()).ToArray();
enum circle { Start=1, Complete=8 }
string GetChar(string bin)
{
try
{
if (Convert.ToInt32(bin, 2).Equals(27))
return EXTENSION_SET_ARRAY[Convert.ToInt32(bin, 2)];
else
return BASIC_SET_ARRAY[Convert.ToInt32(bin, 2)];
}
catch { return string.Empty; }
}
public string DecodeGSM7bit(string strGsm7bit)
{
var suffix = string.Empty;
var septet = string.Empty;
var CurSubstr = string.Empty;
var counter = 1;
List<string> septets = new List<string>();
List<string> sectets = new List<string>();
//Prepare Octets
var octets = Enumerable.Range(0, strGsm7bit.Length / 2).Select(i =>
{
return Convert.ToString(Convert.ToInt64(strGsm7bit.Substring(i * 2, 2), 16), 2).PadLeft(8,'0');
}).ToList();
for (var index=0; index < octets.Count; index = index +1)
{
//Generate Septets
septet = octets[index].Substring(counter);
CurSubstr = octets[index].Substring(0, counter);
if (counter.Equals((int)circle.Start))
septets.Add(septet);
else
septets.Add(septet + suffix);
//Organize Sectets
sectets.Add(GetChar(septets[index]));
suffix = CurSubstr;
counter++;
//Reset counter when the circle is complete.
if (counter == (int)circle.Complete)
{
counter = (int)circle.Start;
sectets.Add(GetChar(suffix));
}
}
return string.Join("", sectets);
}

How to convert Quoted-Print String

I'm working on French String in .NET
Decoding a Mail body , I receive "Chasn=C3=A9 sur illet"
I would like to get "Chasné sur illet"
and i don't find any solution aver 2 days web search.
C# ou VB.NET
Can anyone helps me ?
thanks
Or the easiest of all, just use the QuotedPrintableDecoder from my MimeKit library:
static string DecodeQuotedPrintable (string input, string charset)
{
var decoder = new QuotedPrintableDecoder ();
var buffer = Encoding.ASCII.GetBytes (input);
var output = new byte[decoder.EstimateOutputLength (buffer.Length)];
int used = decoder.Decode (buffer, 0, buffer.Length, output);
var encoding = Encoding.GetEncoding (charset);
return encoding.GetString (output, 0, used);
}
Note that the other answers above assume the decoded content will be ASCII or UTF-8, but that isn't necessarily the case. You'll need to get the charset parameter from the Content-Type header of the MIME part that you are decoding.
Of course... if you don't know how to get that info, you could simply use my awesome MailKit library to get the MIME part from IMAP and have it do all of this work for you.
This is UTF8 encoding.
Using this post:
http://www.dpit.co.uk/decoding-quoted-printable-email-in-c/
Here is the code (don't forget to accept the answer if helped):
using System;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(DecodeQuotedPrintable("Chasn=C3=A9 sur illet"));
Console.ReadKey();
}
static string DecodeQuotedPrintable(string input)
{
var occurences = new Regex(#"(=[0-9A-Z][0-9A-Z])+", RegexOptions.Multiline);
var matches = occurences.Matches(input);
foreach (Match m in matches)
{
byte[] bytes = new byte[m.Value.Length / 3];
for (int i = 0; i < bytes.Length; i++)
{
string hex = m.Value.Substring(i * 3 + 1, 2);
int iHex = Convert.ToInt32(hex, 16);
bytes[i] = Convert.ToByte(iHex);
}
input = input.Replace(m.Value, Encoding.UTF8.GetString(bytes));
}
return input.Replace("=rn", "");
}
}
}
From : https://stackoverflow.com/a/36803911/6403521
My solution :
[TestMethod]
public void TestMethod1()
{
Assert.AreEqual("La Bouichère", quotedprintable("La Bouich=C3=A8re", "utf-8"));
Assert.AreEqual("Chasné sur illet", quotedprintable("Chasn=C3=A9 sur illet", "utf-8"));
Assert.AreEqual("é è", quotedprintable("=C3=A9 =C3=A8", "utf-8"));
}
private string quotedprintable(string pStrIn, string encoding)
{
String strOut = pStrIn.Replace("=\r\n", "");
// Find the first =
int position = strOut.IndexOf("=");
while (position != -1)
{
// String before the =
string leftpart = strOut.Substring(0, position);
// get the QuotedPrintable String in a ArrayList
System.Collections.ArrayList hex = new System.Collections.ArrayList();
// The first Part
hex.Add(strOut.Substring(1 + position, 2));
// Look for the next parts
while (position + 3 < strOut.Length && strOut.Substring(position + 3, 1) == "=")
{
position = position + 3;
hex.Add(strOut.Substring(1 + position, 2));
}
// In the hex Array, we have two items
// Convert using the GetEncoding Function
byte[] bytes = new byte[hex.Count];
for (int i = 0; i < hex.Count; i++)
{
bytes[i] = System.Convert.ToByte(new string(((string)hex[i]).ToCharArray()), 16);
}
string equivalent = System.Text.Encoding.GetEncoding(encoding).GetString(bytes);
// Part of the orignal String after the last QP Symbol
string rightpart = strOut.Substring(position + 3);
// Re build the String
strOut = leftpart + equivalent + rightpart;
// find the new QP Position
position = leftpart.Length + equivalent.Length;
if (rightpart.Length == 0)
{
position = -1;
}
else
{
position = strOut.IndexOf("=", position + 1);
}
}
return strOut;
}
We had an issue with this method - that it is VERY slow.
The following enhanced performance A LOT
public static string FromMailTransferEncoding(this string messageText, Encoding enc, string transferEncoding)
{
if (string.IsNullOrEmpty(transferEncoding))
return messageText;
if ("quoted-printable".Equals(transferEncoding.ToLower()))
{
StringBuilder sb = new StringBuilder();
string delimitorRegEx = #"=[\r][\n]";
string[] parts = Regex.Split(messageText, delimitorRegEx);
foreach (string part in parts)
{
string subPart = part;
Regex occurences = new Regex(#"(=[0-9A-Z][0-9A-Z])+", RegexOptions.Multiline);
MatchCollection matches = occurences.Matches(subPart);
foreach (Match m in matches)
{
byte[] bytes = new byte[m.Value.Length / 3];
for (int i = 0; i < bytes.Length; i++)
{
string hex = m.Value.Substring(i * 3 + 1, 2);
int iHex = Convert.ToInt32(hex, 16);
bytes[i] = Convert.ToByte(iHex);
}
subPart = occurences.Replace(subPart, enc.GetString(bytes), 1);
}
sb.Append(subPart);
}
return sb.ToString();
}
return messageText;
}
static string ConverFromHex(string source)
{
string target = string.Empty;
int startPos = source.IndexOf('=', 0);
int prevStartPos = 0;
while (startPos >= 0)
{
// concat with substring from source
target += source.Substring(prevStartPos, startPos - prevStartPos);
// next offset
startPos++;
// update prev pos
prevStartPos = startPos;
// get substring
string hexString = source.Substring(startPos, 2);
// get int equiv
int hexNum = 0;
if (int.TryParse(hexString, System.Globalization.NumberStyles.AllowHexSpecifier, System.Globalization.CultureInfo.InvariantCulture, out hexNum))
{
// add to target string
target += (char)hexNum;
// add hex length
prevStartPos += 2;
}
// next occurence
startPos = source.IndexOf('=', startPos);
}
// add rest of source
target += source.Substring(prevStartPos);
return target;
}

How to pass string between c++ and c# with null characters inside?

In C++ I have some strings, for example
string str = "a\0b\0c";
And I need to pass this string to C# without losing data after "\0",and from c# pass to C++ also without losing data.
Can you help me?
Ok, I found answer for my question.Maybe, it`s not very good solution, but it fix my problem.
C++:
string EncodeConfigString(string OptionsString)
{
string tempOptions = " ";
if (OptionsString.size() != 0)
{
vector<int> arrayOfIntCodes;
for (int i = 0; i < OptionsString.size(); i++)
{
int codeOfChar = OptionsString[i];
tempOptions += std::to_string(codeOfChar) + "&";
}
}
return tempOptions;
}
C#:
private string DecodeConfig(StringBuilder OptionsBuilder)
{
string result = String.Empty;
string Options = OptionsBuilder.ToString();
if (!string.IsNullOrEmpty(Options) && Options.Contains(Consts.AMPERSAND))
{
string[] entries = Options.Split(Consts.AMPERSAND);
StringBuilder chars = new StringBuilder(Consts.OUTPUT_MAX_SIZE);
for (int i = 0; i < entries.Length; i++)
{
int resultParse;
if (int.TryParse(entries[i], out resultParse))
{
chars.Append((char)resultParse);
}
}
result = chars.ToString();
}
return result;
}

How to cast an 'int' to a 'char' in C#?

I have a string variable which has a mixture of numbers and letters. I want to create a new string that only has int values of the previous string variable. So I found two ways to cast int to char. However, they do not work. Here's what I've tried
string onlyNumberString = "";
foreach (char onlyNum in puzzleData)
{
for (int i = 1; i < 10; i++)
{
if (onlyNum == (char)i)
{
onlyNumberString += onlyNum;
}
}
}
and
string onlyNumberString = "";
foreach (char onlyNum in puzzleData)
{
for (int i = 1; i < 10; i++)
{
if (onlyNum == Convert.ToChar(i))
{
onlyNumberString += onlyNum;
}
}
}
Use Char.IsDigit instead, far simpler.
StringBuilder onlyNumber = new StringBuilder();
foreach (char onlyNum in puzzleData)
{
if (Char.IsDigit(onlyNum))
{
onlyNumber.Append(onlyNum);
}
}
int iNum = 2;
char cChar = iNum.ToString()[0];
Will work for x when 0 <= x <= 9.
You can just cast an int to a char it directly:
var myChar = (char)20;
But to do what you want I suggest using a regular expression:
var onlyNumerals = Regex.Replace(myString, #"[^0-9]", "");
The above will replace any character that is not 0-9 with an empty space.
An alternative, using LINQ and char.IsDigit:
var onlyNumeral = new string(myString.Where(c => Char.IsDigit(c)).ToArray());
You can do it as:
string justNumbers = new String(text.Where(Char.IsDigit).ToArray());
A few ways:
(char)int
Or
int.Parse(char.ToString())
Or
Convert.ToChar(int);

Find text in string with C#

How can I find given text within a string? After that, I'd like to create a new string between that and something else. For instance, if the string was:
This is an example string and my data is here
And I want to create a string with whatever is between "my " and " is" how could I do that? This is pretty pseudo, but hopefully it makes sense.
Use this method:
public static string getBetween(string strSource, string strStart, string strEnd)
{
if (strSource.Contains(strStart) && strSource.Contains(strEnd))
{
int Start, End;
Start = strSource.IndexOf(strStart, 0) + strStart.Length;
End = strSource.IndexOf(strEnd, Start);
return strSource.Substring(Start, End - Start);
}
return "";
}
How to use it:
string source = "This is an example string and my data is here";
string data = getBetween(source, "my", "is");
This is the simplest way:
if(str.Contains("hello"))
You could use Regex:
var regex = new Regex(".*my (.*) is.*");
if (regex.IsMatch("This is an example string and my data is here"))
{
var myCapturedText = regex.Match("This is an example string and my data is here").Groups[1].Value;
Console.WriteLine("This is my captured text: {0}", myCapturedText);
}
string string1 = "This is an example string and my data is here";
string toFind1 = "my";
string toFind2 = "is";
int start = string1.IndexOf(toFind1) + toFind1.Length;
int end = string1.IndexOf(toFind2, start); //Start after the index of 'my' since 'is' appears twice
string string2 = string1.Substring(start, end - start);
Here's my function using Oscar Jara's function as a model.
public static string getBetween(string strSource, string strStart, string strEnd) {
const int kNotFound = -1;
var startIdx = strSource.IndexOf(strStart);
if (startIdx != kNotFound) {
startIdx += strStart.Length;
var endIdx = strSource.IndexOf(strEnd, startIdx);
if (endIdx > startIdx) {
return strSource.Substring(startIdx, endIdx - startIdx);
}
}
return String.Empty;
}
This version does at most two searches of the text. It avoids an exception thrown by Oscar's version when searching for an end string that only occurs before the start string, i.e., getBetween(text, "my", "and");.
Usage is the same:
string text = "This is an example string and my data is here";
string data = getBetween(text, "my", "is");
You can do it compactly like this:
string abc = abc.Replace(abc.Substring(abc.IndexOf("me"), (abc.IndexOf("is", abc.IndexOf("me")) + 1) - abc.IndexOf("size")), string.Empty);
Except for #Prashant's answer, the above answers have been answered incorrectly. Where is the "replace" feature of the answer? The OP asked, "After that, I'd like to create a new string between that and something else".
Based on #Oscar's excellent response, I have expanded his function to be a "Search And Replace" function in one.
I think #Prashant's answer should have been the accepted answer by the OP, as it does a replace.
Anyway, I've called my variant - ReplaceBetween().
public static string ReplaceBetween(string strSource, string strStart, string strEnd, string strReplace)
{
int Start, End;
if (strSource.Contains(strStart) && strSource.Contains(strEnd))
{
Start = strSource.IndexOf(strStart, 0) + strStart.Length;
End = strSource.IndexOf(strEnd, Start);
string strToReplace = strSource.Substring(Start, End - Start);
string newString = strSource.Concat(Start,strReplace,End - Start);
return newString;
}
else
{
return string.Empty;
}
}
static void Main(string[] args)
{
int f = 0;
Console.WriteLine("enter the string");
string s = Console.ReadLine();
Console.WriteLine("enter the word to be searched");
string a = Console.ReadLine();
int l = s.Length;
int c = a.Length;
for (int i = 0; i < l; i++)
{
if (s[i] == a[0])
{
for (int K = i + 1, j = 1; j < c; j++, K++)
{
if (s[K] == a[j])
{
f++;
}
}
}
}
if (f == c - 1)
{
Console.WriteLine("matching");
}
else
{
Console.WriteLine("not found");
}
Console.ReadLine();
}
string WordInBetween(string sentence, string wordOne, string wordTwo)
{
int start = sentence.IndexOf(wordOne) + wordOne.Length + 1;
int end = sentence.IndexOf(wordTwo) - start - 1;
return sentence.Substring(start, end);
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Diagnostics;
namespace oops3
{
public class Demo
{
static void Main(string[] args)
{
Console.WriteLine("Enter the string");
string x = Console.ReadLine();
Console.WriteLine("enter the string to be searched");
string SearchText = Console.ReadLine();
string[] myarr = new string[30];
myarr = x.Split(' ');
int i = 0;
foreach(string s in myarr)
{
i = i + 1;
if (s==SearchText)
{
Console.WriteLine("The string found at position:" + i);
}
}
Console.ReadLine();
}
}
}
This is the correct way to replace a portion of text inside a string (based upon the getBetween method by Oscar Jara):
public static string ReplaceTextBetween(string strSource, string strStart, string strEnd, string strReplace)
{
int Start, End, strSourceEnd;
if (strSource.Contains(strStart) && strSource.Contains(strEnd))
{
Start = strSource.IndexOf(strStart, 0) + strStart.Length;
End = strSource.IndexOf(strEnd, Start);
strSourceEnd = strSource.Length - 1;
string strToReplace = strSource.Substring(Start, End - Start);
string newString = string.Concat(strSource.Substring(0, Start), strReplace, strSource.Substring(Start + strToReplace.Length, strSourceEnd - Start));
return newString;
}
else
{
return string.Empty;
}
}
The string.Concat concatenates 3 strings:
The string source portion before the string to replace found - strSource.Substring(0, Start)
The replacing string - strReplace
The string source portion after the string to replace found - strSource.Substring(Start + strToReplace.Length, strSourceEnd - Start)
Simply add this code:
if (string.Contains("search_text")) {
MessageBox.Show("Message.");
}
If you know that you always want the string between "my" and "is", then you can always perform the following:
string message = "This is an example string and my data is here";
//Get the string position of the first word and add two (for it's length)
int pos1 = message.IndexOf("my") + 2;
//Get the string position of the next word, starting index being after the first position
int pos2 = message.IndexOf("is", pos1);
//use substring to obtain the information in between and store in a new string
string data = message.Substring(pos1, pos2 - pos1).Trim();
First find the index of text and then substring
var ind = Directory.GetCurrentDirectory().ToString().IndexOf("TEXT To find");
string productFolder = Directory.GetCurrentDirectory().ToString().Substring(0, ind);
I have different approach on ReplaceTextBetween() function.
public static string ReplaceTextBetween(this string strSource, string strStart, string strEnd, string strReplace)
{
if (strSource.Contains(strStart) && strSource.Contains(strEnd))
{
var startIndex = strSource.IndexOf(strStart, 0) + strStart.Length;
var endIndex = strSource.IndexOf(strEnd, startIndex);
var strSourceLength = strSource.Length;
var strToReplace = strSource.Substring(startIndex, endIndex - startIndex);
var concatStart = startIndex + strToReplace.Length;
var beforeReplaceStr = strSource.Substring(0, startIndex);
var afterReplaceStr = strSource.Substring(concatStart, strSourceLength - endIndex);
return string.Concat(beforeReplaceStr, strReplace, afterReplaceStr);
}
return strSource;
}
Correct answer here without using any pre-defined method.
static void WordContainsInString()
{
int f = 0;
Console.WriteLine("Input the string");
string str = Console.ReadLine();
Console.WriteLine("Input the word to search");
string word = Console.ReadLine();
int l = str.Length;
int c = word.Length;
for (int i = 0; i < l; i++)
{
if (str[i] == word[0])
{
for (int K = i + 1, j = 1; j < c; j++, K++)
{
if (str[K] == word[j])
{
f++;
}
else
{
f = 0;
}
}
}
}
if (f == c - 1)
{
Console.WriteLine("matching");
}
else
{
Console.WriteLine("not found");
}
Console.ReadLine();
}
for .net 6 can use next code
public static string? Crop(string? text, string? start, string? end = default)
{
if (text == null) return null;
string? result;
var startIndex = string.IsNullOrEmpty(start) ? 0 : text.IndexOf(start);
if (startIndex < 0) return null;
startIndex += start?.Length ?? 0;
if (string.IsNullOrEmpty(end))
{
result = text.Substring(startIndex);
}
else
{
var endIndex = text.IndexOf(end, startIndex);
if (endIndex < 0) return null;
result = text.Substring(startIndex, endIndex - startIndex);
}
return result;
}

Categories

Resources