I have a string. For example :
string a = "abcdef098403248";
My goal is, knowing that the string ends with a number (else something like this will happen : MessageBox.Show("String doesnt end in a number"); ), i want to read the string, starting from the end to the begining, and store the values in another string.
Now the only problem is, i can only store in that new string numbers, and when i read the string a , while i count from the back to end if i find a character that isnt a number, i stop reading and store the previous numbers found in the new string. The code output should look somthing like this:
string a = "aBcdef3213BBBBB0913456";
//part were i read the string from back to end
string finalString = "0913456";
As you see there, i store the numbers from left to right, but i want to read them from right to left.
Another example of what i want:
string a = "aaaaa3a224444";
// part were i read the string from back to end
string finalString = "224444";
Or:
string a = "3333333a224444";
// part were i read the string from back to end
string finalString = "224444";
Regardless, thanks.
Stack<char> is your friend:
var stack = new Stack<char>();
foreach (var c in a.Reverse())
{
if (!char.IsDigit(c))
break;
stack.Push(c);
}
return new string(stack.ToArray());
Reverse the string using the function below.
Grab the number the wrong way around - spin it back.
public static string Reverse( string s )
{
char[] charArray = s.ToCharArray();
Array.Reverse( charArray );
return new string( charArray );
}
Taken from : Best way to reverse a string
string str = "3333333a224444";
var reversedStr = str.Reverse();
string result= new String(reversedStr.TakeWhile(Char.IsDigit).ToArray());
I came up with this. Not as elegant as others. It adds the numbers to the string until it encounters a letter again then stops.
string a = "aBcdef3213BBBBB0913456";
var charList = a.ToCharArray();
string newString = string.Empty;
foreach (var letter in charList.Reverse())
{
var number = 0;
if (Int32.TryParse(letter.ToString(), out number))
{
newString = string.Format("{0}{1}", letter, newString);
}
else
{
break;
}
}
string a = "saffsa1ad12314";
string finalString = string.Empty;
char[] chars = a.ToCharArray();
for (int i = chars.Length -1; i >= 0; i--)
{
if (char.IsDigit(chars[i]))
{
finalString += chars[i];
}
else
{
break; //so you dont get a number after a letter
//could put your mbox here
}
}
//Now you just have to reverse the string
char[] revMe = finalString.ToCharArray();
Array.Reverse(revMe);
finalString = string.Empty;
foreach (char x in revMe)
{
finalString += x;
}
Console.WriteLine(finalString);
//outputs: 12314
This question feels awfully homeworky - but here is a very verbose way
of solving your problem. Alternatively you can read up on regex in c#.
Related
I have a string which has multiple spaces between the words and I want to remove these spaces and then bring them back .. The problem was in bringing the spaces back after deleting them I tried to code my idea but it runs without any output and some times it gives me an exception of "Index was outside of array bounds" .. any help
string pt = "My name is Code"
int ptLenght = pt.Length;
char[] buffer1 = pt.ToCharArray();
spaceHolder = new int[pt.Length];
for (int m = 0; m < pt.Length; m++)
{
if (buffer1[m] == ' ')
{
hold = m;
spaceHolder[m] = hold;
}
}
char[] buffer = pt.Replace(" ", string.Empty).ToCharArray();
int stringRemovedSpaces = pt.Length;
char[] buffer = pt.ToCharArray(); // source
char[] buffer2 = new char[ptLenght]; // destination
for (int i = 0; i < pt.Length; i++)
{
buffer2[i] = buffer[i];
}
for (int i = 0; i < buffer2.Length; i++)
{
if (i == spaceHolder[i])
{
for (int m = stringRemovedSpaces; m <= i; m--)
{
buffer2[m-1] = buffer2[m];
}
buffer2[i] = ' ';
}
}
return new string(buffer2);
I suspect that you want to replace multiple spaces with a single one. The fastest and easiest way to do this is with a simple regular expression that replaces multiple whitespaces with a single space, eg:
var newString = Regex.Replace("A B C",#"\s+"," ")
or
var newString = Regex.Replace("A B C",#"[ ]+"," ")
The reason this is fastest than other methods like repeated string replacements is that a regular expression does not generate temporary strings. Internatlly it generates a list of indexes to matching items. A string is generated only when the code asks for a string value, like a match or replacement.
A regular expression object is thread-safe as well. You can create it once, store it in a static field and reuse it :
static Regex _spacer = new Regex(#"\s+");
public void MyMethod(string someInput)
{
...
var newString=_spacer.Replace(someInput, " ");
...
}
Deleting all the spaces in a string is really just as simple as calling the Replace function on a string. Please note that when you call Replace on a string, it does not modify the original string, it creates and returns a new string. I only bring this up because you set two different integer variables to pt.Length, and at no point is the string pt actually modified. Also, I would imagine you are getting the "Index was outside of array bounds" from the nested for loop. You have the loop set up in a way that m will decrement forever. However, once m equals zero, you will be trying to access an index of -1 from buffer2, which is a no no. If you want to delete the spaces while retaining an original copy of the string you could simplify your code to this:
string pt = "My name is Code";
string newpt = pt.Replace(" ", string.empty);
pt is a string with spaces, newpt is a new string with spaces removed. However, if you want to replace multiple consecutive spaces with a single space, I would recommend following the answer Panagiotis Kanavos gave.
I followed the advice of #maccettura and I did it like this and it worked as I wished :)
string orignalString = "";
orignalString = pt;
char[] buffer = pt.ToCharArray();
orignalString = new string(buffer);
return orignalString.Replace(" ", string.Empty);
// Here I got the string without spaces , now I have the same string with and without spaces
Everyone knows how to replace a character in a string with:
string text = "Hello World!";
text = text.Replace("H","J");
but what I need is to replace multiple characters in a string
something like:
string text = textBox1.Text;
text = text.Replace("a","b")
text = text.Replace("b","a")
now the result is aa , but if the user types ab I want the result to be ba
There's multiple ways to do this.
Using a loop
char[] temp = input.ToCharArray();
for (int index = 0; index < temp.Length; index++)
switch (temp[index])
{
case 'a':
temp[index] = 'b';
break;
case 'b':
temp[index] = 'a';
break;
}
string output = new string(temp);
This will simply copy the string to a character array, fix each character by itself, then convert the array back into a string. No risk of getting any of the characters confused with any of the others.
Using a regular expression
You can exploit this overload of Regex.Replace:
public static string Replace(
string input,
string pattern,
MatchEvaluator evaluator
)
This takes a delegate that will be called for each match, and return the final result. The delegate is responsible for returning what each match should be replaced with.
string output = Regex.Replace(input, ".", ma =>
{
if (ma.Value == "a")
return "b";
if (ma.Value == "b")
return "a";
return ma.Value;
});
For your particular requirement I would suggest you to use like the following:
string input = "abcba";
string outPut=String.Join("",input.ToCharArray()
.Select(x=> x=='a'? x='b':
(x=='b'?x='a':x))
.ToArray());
The output string will be bacab for this particular input
Do not call String.Replace multiple times for the same string! It creates a new string every time (also it has to cycle through the whole string every time) causing memory pressure and processor time waste if used a lot.
What you could do:
Create a new char array with the same length as the input string. Iterate over all chars of the input strings. For every char, check whether it should be replaced. If it should be replaced, write the replacement into the char array you created earlier, otherwise write the original char into that array. Then create a new string using that char array.
string inputString = "aabbccdd";
char[] chars = new char[inputString.Length];
for (int i = 0; i < inputString.Length; i++)
{
if (inputString[i] == 'a')
{
chars[i] = 'b';
}
else if (inputString[i] == 'b')
{
chars[i] = 'a';
}
else
{
chars[i] = inputString[i];
}
}
string outputString = new string(chars);
Consider using a switch when intending to replace a lot of different characters.
Use should use StringBuilder when you are concatenating many strings in a loop like this, so I suggest the following solution:
StringBuilder sb = new StringBuilder(text.Length);
foreach(char c in text)
{
sb.Append(c == 'a' ? 'b' : 'a');
}
var result = sb.ToString();
I have a situation where i don't want to compare total string length to other string .
Example:
string MainString = "Deanna Ecker";
string SearchString = "Ecker Designs";
int value = MainString.IndexOf(SearchString);
here it is searching with whole string. but i need to find any word in MainString. not with whole string..
Let me know how is this possible.
If case-sensitivity is not an issue, you could split both strings by the space, then intersect the two lists to see if there are any matches:
var foundWords = MainString.Split(' ').Intersect(SearchString.Split(' '));
Or if you only want to know if a word was found:
var isMatch = MainString.Split(' ').Intersect(SearchString.Split(' ')).Any();
you can convert your string to a char array then search each character via looping from all characters
such that
public bool MatchString(string first,string second)
{
char[] ch1=first.ToCharArray();
char[] ch2=second.ToCharArray();
bool match=false;
for(int i=0 ; i<ch1.length ; i++)
{
for(int j=0 ; j<ch2.length ; j++)
{
if(ch2[j]==ch[i])
{
match=true;
break;
}
}
}
return match;
}
Try: var wordMatch = MainString.Split(' ').Intersect(SearchString.Split(' ')).Any();
How to delete every 2nd character in a string?
For example:
3030313535333635 -> 00155365
3030303336313435 -> 00036145
3032323437353530 -> 02247550
The strings are always 16-characters long and the result is always 8 characters long - and the character that is being removed is always a '3' - Don't ask why however - I did not dream up this crazy source data.
Try this to get the every other character from the string:-
var s = string.Join<char>("", str.Where((ch, index) => (index % 2) != 0));
String input = "3030313535333635";
String result = "";
for(int i = 1; i < 16; i +=2 )
{
result += input[i];
}
You can use this well-known class System.Runtime.Remoting.Metadata.W3cXsd2001.SoapHexBinary :)
string str = "3030313535333635";
var hex = System.Runtime.Remoting.Metadata.W3cXsd2001.SoapHexBinary.Parse(str);
var newstr = Encoding.ASCII.GetString(hex.Value);
Using a StringBuilder to create a string will save resources
string input = "3030313535333635";
var sb = new StringBuilder(8); // Specify capacity = 8
for (int i = 1; i < 16; i += 2) {
sb.Append(input[i]);
}
string result = sb.ToString();
Code in Java Language
String input= "3030313535333635"
String output="";
for(int i=1;i<input.length();i=i+2)
{
output+=input.charAt(i).toString();
}
System.out.println(output);
I am scraping some website content which is like this - "Company Stock Rs. 7100".
Now, what i want is to extract the numeric value from this string. I tried split but something or the other goes wrong with my regular expression.
Please let me know how to get this value.
Use:
var result = Regex.Match(input, #"\d+").Value;
If you want to find only number which is last "entity" in the string you should use this regex:
\d+$
If you want to match last number in the string, you can use:
\d+(?!\D*\d)
int val = int.Parse(Regex.Match(input, #"\d+", RegexOptions.RightToLeft).Value);
I always liked LINQ:
var theNumber = theString.Where(x => char.IsNumber(x));
Though Regex sounds like the native choice...
This code will return the integer at the end of the string. This will work better than the regular expressions in the case that there is a number somewhere else in the string.
public int getLastInt(string line)
{
int offset = line.Length;
for (int i = line.Length - 1; i >= 0; i--)
{
char c = line[i];
if (char.IsDigit(c))
{
offset--;
}
else
{
if (offset == line.Length)
{
// No int at the end
return -1;
}
return int.Parse(line.Substring(offset));
}
}
return int.Parse(line.Substring(offset));
}
If your number is always after the last space and your string always ends with this number, you can get it this way:
str.Substring(str.LastIndexOf(" ") + 1)
Here is my answer ....it is separating numeric from string using C#....
static void Main(string[] args)
{
String details = "XSD34AB67";
string numeric = "";
string nonnumeric = "";
char[] mychar = details.ToCharArray();
foreach (char ch in mychar)
{
if (char.IsDigit(ch))
{
numeric = numeric + ch.ToString();
}
else
{
nonnumeric = nonnumeric + ch.ToString();
}
}
int i = Convert.ToInt32(numeric);
Console.WriteLine(numeric);
Console.WriteLine(nonnumeric);
Console.ReadLine();
}
}
}
You can use \d+ to match the first occurrence of a number:
string num = Regex.Match(input, #"\d+").Value;