How to check where a string belongs to a string [duplicate] - c#

My code is this:
string dex = "ABCD1234";
string ch = "C";
string ch1, ch2;
if (dex.Contains(ch))
{
string n = Convert.ToChar(dex);
MessageBox.Show(ch + " is on " + n + " place and is between " + ch1 + " and " + ch2);
}
I wanted to convert the string into array but i can't do it and i can't retrieve the position of the 'ch' string and what's between it.
The output should be:
MessageBox.Show("C is on 3rd place and is between B and D");

string aS = "ABCDEFGHI";
char ch = 'C';
int idx = aS.IndexOf(ch);
MessageBox.Show(string.Format("{0} is in position {1} and between {2} and {3}", ch.ToString(), idx + 1, aS[idx - 1], aS[idx + 1]));
This wont handle if your character is at position zero and some other conditions, you'll have to figure them out.

You might want to read the documentation on System.String and its methods and properties:
The method you want is IndexOf():
string s = "ABCD1234" ;
char c = 'C' ;
int offset = s.IndexOf(c) ;
bool found = index >= 0 ;
if ( !found )
{
Console.WriteLine( "string '{0}' does not contain char '{1}'" , s , c ) ;
}
else
{
string prefix = s.Substring(0,offset) ;
string suffix = s.Substring(offset+1) ;
Console.WriteLine( "char '{0}' found at offset +{1} in string '{2}'." , c , offset , s ) ;
Console.WriteLine( "The substring before it is '{0}'." , prefix ) ;
Console.WriteLine( "The substring following it is '{0}'." , suffix ) ;
}

Related

How to split string by number of characters and add at the begin of each string custom string

For example I have some string, length of this string = 2900
How can I divide this string by parts(length 255) and add for each part "Part {number}" + dividing string
On input: string (2900 length)
Output: List with 12 element and each element should be = Part {number} + substring and length less than 255
I try smth like that, but I have trouble when I have more than 9 part
public static IEnumerable<string> SplitJobComment(string str, int chunkLength)
{
var partNumber = 1;
var partNumberTemplate = $"Part {partNumber} ";
chunkLength -= partNumberTemplate.Length;
for (var i = 0; i < str.Length; i += chunkLength)
{
if (chunkLength + i > str.Length)
{
chunkLength = str.Length - i;
}
partNumberTemplate = $"Part {partNumber} ";
partNumber++;
yield return partNumberTemplate + str.Substring(i, chunkLength);
}
}
Given that the real problem, as I assumed, is the fact that partNumberTemplate's length changes when partNumber>9, one possibile solution can be
var partNumberTemplate = $"Part {partNumber:D2} ";
{partNumber:D2} formats the number using always 2 digits.

`if` statement not working correctly

I am trying to make a console application for my programming class. The if statement is not working correctly. I want it to count the string length and if it's greater than 10000 or less than 0, go to the else statement. But it doesn't and continues the if statement.
static void Main(string[] args)
{
Console.WriteLine("Input a year from 0 to 10000 to determine the next year with distinct numbers");
string a = Console.ReadLine();
int MaxLength = 10000;
int MinLength = 0;
if (a.Length <= MaxLength && a.Length >= MinLength)
{
string b = a.Substring(0, 1);
string b1 = a.Substring(1, 1);
string b2 = a.Substring(2, 1);
string b3 = a.Substring(3, 1);
Console.WriteLine(b + " " + b1 + " " + b2 + " " + b3);
}
else
{
Console.WriteLine("Error");
}
Console.ReadKey();
}
You have to use int.Parse(a).
if (int.Parse(a) <= MaxLength && int.Parse(a) >= MinLength)
{
string b = a.Substring(0, 1);
string b1 = a.Substring(1, 1);
string b2 = a.Substring(2, 1);
string b3 = a.Substring(3, 1);
Console.WriteLine(b + " " + b1 + " " + b2 + " " + b3);
}
else
{
Console.WriteLine("Error");
}
Your code is checking the length of the string input - so if a user enters, for example, 100 the length will be three.
A length of a string can never be less than zero, and I very much doubt it will ever be longer than 10000.
Perhaps what you were actually trying to do is convert the user's entry to a number, while also keeping th ability to use the Substring method from the users input as a set of characters.
In which case, you want 2 variables
The original user input (a string, where you can use Substring) - a from your original code
A numerical representation of the input for which you can compare to a min & max number. val in the code below
Another consideration is that the user may enter a value which is not convertable to a number, so
A boolean indicating that the user has entered a valid number. isValidEntry in the code below
Console.WriteLine("Input a year from 0 to 10000 to determine the next year with distinct numbers");
string a = Console.ReadLine();
int MaxLength = 10000;
int MinLength = 0;
int val = 0;
bool isValidEntry = int.TryParse(a, out val);
if (isValidEntry && val <= MaxLength && val >= MinLength)
{
string b = a.Substring(0, 1);
string b1 = a.Substring(1, 1);
string b2 = a.Substring(2, 1);
string b3 = a.Substring(3, 1);
Console.WriteLine(b + " " + b1 + " " + b2 + " " + b3);
}
else
{
Console.WriteLine("Error");
}
Console.ReadKey();
I believe there is some confusion on what you are doing. Your description says you are trying to count the amount of characters in the inputed string. In which case you will need a string with more that 10000 characters to go the else statement.
However your program code claims you just want the numerical value of your string. Therefore you should try using a conversion method.
int x = int.Parse(a);
Obviously you need to do bound checking on x instead of a afterwards.

How to get the specific sub-string position in a string

I have a string 121712 1512 0025 64559 7259181568 701 013 2.Now as per my requirement i have to get the last sub-string 2 StartIndex and EndIndex .But here the issue is with the point that 2 is coming in the first substring 121712 so it is taking from there which i dont want ..
Here is the code that i have tried..
string s = "121712 1512 0025 64559 7259181568 701 013 2 ";
string inout = "2";
string[] arrs = s.Split(' ');
for (int i = 0; i <= arrs.Length; i++)
{
string str = arrs[i];
if (str == inout)
{
int startIndex = s.IndexOf(arrs[i]);
int endIndex = s.IndexOf(" ", startIndex);
int difference = endIndex - startIndex;
string inoutSubstring = (startIndex + "," + difference);
}
}
Please help me to resolve the issue ..Thanks.
You said last substring Right??
s.LastIndexOf(inout) will give the starting index of Inout string. Now I need to get endindex of Inout in s string. add inout.Lenght-1 into s.LastIndexOf(inout) that will give Last index of inout string.
You can do for any string just assign new sting int inout variable like of "21" , "12" or many other.
string inout = "2";
int startIndex;
int endIndex;
startIndex = s.LastIndexOf(inout);
endIndex = startIndex + inout.Length-1;
If I understand you correctly, you want to find the last incidence of a substring within a string. The String object in C# has a method designed for exactly this, String.LastIndexOf:
string s = "121712 1512 0025 64559 7259181568 701 013 2 ";
string inout = "2";
string[] arrs = s.Split(' ');
for (int i = 0; i <= arrs.Length; i++)
{
string str = arrs[i];
if (str == inout)
{
int startIndex = s.IndexOf("2");
int endIndex = s.LastIndexOf("2");
}
}
Note that both of these methods will return -1 if they can't find an incidence of the substring. Additionally, if there's only a single incidence of a substring, they'll both return the same value.

Converting string or char to int

I'm totally puzzled
string temp = "73";
int tempc0 = Convert.ToInt32(temp[0]);
int tempc1 = Convert.ToInt32(temp[1]);
MessageBox.Show(tempc0 + "*" + tempc1 + "=" + tempc0*tempc1);
I would expect: 7*3=21
But then I receive: 55*51=2805
That is the ASCII value for the character 7 and 3. If you want number representation then you can convert each character to string and then use Convert.ToString:
string temp = "73";
int tempc0 = Convert.ToInt32(temp[0].ToString());
int tempc1 = Convert.ToInt32(temp[1].ToString());
MessageBox.Show(tempc0 + "*" + tempc1 + "=" + tempc0*tempc1);
55 and 51 are their locations in the ascii chart.
Link to chart - http://kimsehoon.com/files/attach/images/149/759/007/ascii%281%29.png
try using int.parse
This works:
string temp = "73";
int tempc0 = Convert.ToInt32(temp[0].ToString());
int tempc1 = Convert.ToInt32(temp[1].ToString());
Console.WriteLine(tempc0 + "*" + tempc1 + "=" + tempc0 * tempc1);
You have to do ToString() to get the actual string representation.
You are getting the ASCII codes for 7 and 3, which are 55 and 51 respectively.
Use int.Parse() to convert a char or string to a value.
int tempc0 = int.Parse(temp[0].ToString());
int tempc1 = int.Parse(temp[1].ToString());
int product = tempc0 * tempc1; // 7 * 3 = 21
int.Parse() doesn't accept a char as a parameter, so you have to convert to string first, or use temp.SubString(0, 1) instead.
This works, and is more computationally efficient than using either int.Parse() or Convert.ToInt32():
string temp = "73";
int tempc0 = temp[0] - '0';
int tempc1 = temp[1] - '0';
MessageBox.Show(tempc0 + "*" + tempc1 + "=" + tempc0 * tempc1);
Converting a character to an integer gives you the Unicode character code. If you convert a string to integer it will be parsed as a number:
string temp = "73";
int tempc0 = Convert.ToInt32(temp.Substring(0, 1));
int tempc1 = Convert.ToInt32(temp.Substring(1, 1));
When you write string temp = "73", your temp[0] and temp[1] are being char values.
From Convert.ToInt32 Method(Char) method
Converts the value of the specified Unicode character to the
equivalent 32-bit signed integer.
That means converting a char to an int32 gives you the unicode character code.
You just need to use .ToString() method your your temp[0] and temp[1] values. Like;
string temp = "73";
int tempc0 = Convert.ToInt32(temp[0].ToString());
int tempc1 = Convert.ToInt32(temp[1].ToString());
MessageBox.Show(tempc0 + "*" + tempc1 + "=" + tempc0*tempc1);
Here is a DEMO.

How to get ASCII value of string in C#

I want to get the ASCII value of characters in a string in C#.
If my string has the value "9quali52ty3", I want an array with the ASCII values of each of the 11 characters.
How can I get ASCII values in C#?
From MSDN
string value = "9quali52ty3";
// Convert the string into a byte[].
byte[] asciiBytes = Encoding.ASCII.GetBytes(value);
You now have an array of the ASCII value of the bytes. I got the following:
57
113
117
97
108
105
53
50
116
121
51
string s = "9quali52ty3";
foreach(char c in s)
{
Console.WriteLine((int)c);
}
This should work:
string s = "9quali52ty3";
byte[] ASCIIValues = Encoding.ASCII.GetBytes(s);
foreach(byte b in ASCIIValues) {
Console.WriteLine(b);
}
Do you mean you only want the alphabetic characters and not the digits? So you want "quality" as a result? You can use Char.IsLetter or Char.IsDigit to filter them out one by one.
string s = "9quali52ty3";
StringBuilder result = new StringBuilder();
foreach(char c in s)
{
if (Char.IsLetter(c))
result.Add(c);
}
Console.WriteLine(result); // quality
string text = "ABCD";
for (int i = 0; i < text.Length; i++)
{
Console.WriteLine(text[i] + " => " + Char.ConvertToUtf32(text, i));
}
If I remember correctly, the ASCII value is the number of the lower seven bits of the Unicode number.
string value = "mahesh";
// Convert the string into a byte[].
byte[] asciiBytes = Encoding.ASCII.GetBytes(value);
for (int i = 0; i < value.Length; i++)
{
Console.WriteLine(value.Substring(i, 1) + " as ASCII value of: " + asciiBytes[i]);
}
This program will accept more than one character and output their ASCII value:
using System;
class ASCII
{
public static void Main(string [] args)
{
string s;
Console.WriteLine(" Enter your sentence: ");
s = Console.ReadLine();
foreach (char c in s)
{
Console.WriteLine((int)c);
}
}
}
Or in LINQ:
string value = "9quali52ty3";
var ascii_values = value.Select(x => (int)x);
var as_hex = value.Select(x => ((int)x).ToString("X02"));
If you want the charcode for each character in the string, you could do something like this:
char[] chars = "9quali52ty3".ToCharArray();
byte[] asciiBytes = Encoding.ASCII.GetBytes("Y");
foreach (byte b in asciiBytes)
{
MessageBox.Show("" + b);
}
Earlier responders have answered the question but have not provided the information the title led me to expect. I had a method that returned a one character string but
I wanted a character which I could convert to hexadecimal. The following code demonstrates what I thought I would find in the hope it is helpful to others.
string s = "\ta£\x0394\x221A"; // tab; lower case a; pound sign; Greek delta;
// square root
Debug.Print(s);
char c = s[0];
int i = (int)c;
string x = i.ToString("X");
c = s[1];
i = (int)c;
x = i.ToString("X");
Debug.Print(c.ToString() + " " + i.ToString() + " " + x);
c = s[2];
i = (int)c;
x = i.ToString("X");
Debug.Print(c.ToString() + " " + i.ToString() + " " + x);
c = s[3];
i = (int)c;
x = i.ToString("X");
Debug.Print(c.ToString() + " " + i.ToString() + " " + x);
c = s[4];
i = (int)c;
x = i.ToString("X");
Debug.Print(c.ToString() + " " + i.ToString() + " " + x);
The above code outputs the following to the immediate window:
a£Δ√
a 97 61
£ 163 A3
Δ 916 394
√ 8730 221A
You can remove the BOM using:
//Create a character to compare BOM
char byteOrderMark = (char)65279;
if (sourceString.ToCharArray()[0].Equals(byteOrderMark))
{
targetString = sourceString.Remove(0, 1);
}
I want to get the ASCII value of characters in a string in C#.
Everyone confer answer in this structure.
If my string has the value "9quali52ty3", I want an array with the ASCII values of each of the 11 characters.
but in console we work frankness so we get a char and print the ASCII code if i wrong so please correct my answer.
static void Main(string[] args)
{
Console.WriteLine(Console.Read());
Convert.ToInt16(Console.Read());
Console.ReadKey();
}
Why not the old fashioned easy way?
public int[] ToASCII(string s)
{
char c;
int[] cByte = new int[s.Length]; / the ASCII string
for (int i = 0; i < s.Length; i++)
{
c = s[i]; // get a character from the string s
cByte[i] = Convert.ToInt16(c); // and convert it to ASCII
}
return cByte;
}
string nomFile = "9quali52ty3";
byte[] nomBytes = Encoding.ASCII.GetBytes(nomFile);
string name = "";
foreach (byte he in nomBytes)
{
name += he.ToString("X02");
}
`
Console.WriteLine(name);
// it's` better now ;)

Categories

Resources