C# Replace string by position [closed] - c#

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am trying to replace a comma in a string.
For example, the data is the currency value of a part.
Eg. 453,27 This is the value I get from an SAP database
I need to replace the comma to a period to fix the value to the correct amount. Now sometimes, it will be in the thousands.
Eg. 2,356,34 This value needs to be 2,356.34
So, I need help manipulating the string to replace comma that is 2 characters from the end.
Thanks for the help

string a = "2,356,34";
int pos = a.LastIndexOf(',');
string b = a.Substring(0, pos) + "." + a.Substring(pos+1);
You'll need to add a bit of checking for cases where there are no commas in the string, etc. but that's the core code.
You could also do it with a regex, but this is simple and reasonably efficient.

A quick google search gave me this:
void replaceCharWithChar(ref string text, int index, char charToUse)
{
char[] tmpBuffer = text.ToCharArray();
buffer[index] = charToUse;
text = new string(tmpBuffer);
}
So your "charToUse" should be '.'. If it always is 2 characters from end, your index should be
text.length - 3.
http://www.dreamincode.net/code/snippet1843.htm

If I understand correctly, you always need to replace the last comma with a period.
public string FixSAPNumber(string number)
{
var str = new StringBuilder(number);
str[number.LastIndexOf(',')] = '.';
return str.ToString();
}

string item_to_replace = "234,45";
var item = decimal.Parse(item_to_replace);
var new_item = item/100;
//if you need new_item as string
//then new_item.ToString(Format)

Use this :
string str = "2,356,34";
string[] newStr = str.Split(',');
str = string.Empty;
for (int i = 0; i <= newStr.Length-1; i++)
{
if (i == newStr.Length-1)
{
str += "."+newStr[i].ToString();
}
else if (i == 0)
{
str += newStr[i].ToString();
}
else
{
str += "," + newStr[i].ToString();
}
}
string s = str;

string x = "2,356,34";
if (x[x.Length - 3] == ',')
{
x = x.Remove(x.Length - 3, 1);
x = x.Insert(x.Length - 2, ".");
}

Related

Hi i'm a newbie in c# and i'm trying to write trimleft function by myself [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Improve this question
public static string TrimLeft(string word)
{
int numberOfLetters = 0;
foreach (var c in word)
{
numberOfLetters++;
}
int start = 0, end = numberOfLetters - 1;
string b = "";
for (int i = 0; i < numberOfLetters; i++)
{
if (!char.IsWhiteSpace(word[i]))
{
start = i;
b += word[i];
}
}
Console.WriteLine("Trimmed version: {0}", b);
return word;
}
i'm trying to write trimleft function by myself i couldnt quite figure out how i did the normal trim version but how can i do the trimleft version of it without using any inbuilt string. functions like substring etc.
this is a shorter version, it was tested and working properly
public static string TrimLeft(string word)
{
string result = "";
bool trimDone = false;
foreach (var chr in word)
{
if (chr == ' ' && !trimDone) continue;
result = result + chr;
trimDone = true;
}
Console.WriteLine("Trimmed version: {0}", result);
return result;
}
test
var word = " abc def !";
word = TrimLeft(word);
result
abc def !
Somebody could suggest a string builder, but as I understand it is out of the scope of the project
also there is another version but I think that it is out of the scope too
public static string TrimLeft(string word)
{
var i = 0;
foreach (var chr in word)
{
if (chr != ' ')
{
if ( i > 0)
{
Console.WriteLine($"Trimmed version:{word[i..]}");
return word[i..];
}
else break;
}
i++;
}
Console.WriteLine($"Nothing To Trim : {word}");
return word;
}
Find the index of the first non-space character in your input string, then copy the rest to your result string and return it.
The first non-space char can be found with a loop and the copy operation can also be done with a loop, if IndexOf or Substring are not allowed when solving this problem. A string builder could be used to efficiently build your result string.
Another way to do it is:
public static string TrimLeft(string word)
{
int i = 1;
foreach (var chr in word)
{
if (chr != ' ') break;
i++;
}
i--;
return word[i..];
}
see: Fiddle

how to get words from string without SPLIT in c# [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm stack with a task which ask for "read from console" (C#) a text (string) and get words separated by spaces.
for example: phrase=**"i love this world love"** BUT I need to try this WITHOUT methods or functions like SPLIT or REGEX or similar.
I need to compare 2 words and I dont know how to catch 'em in separated word1 word2 fullphrase.
What i want is word1="this" word2= "world" AND CHECK if there are 2 words REPEATED
string frase, palabra1="",pal2="";
bool si = false;
Console.WriteLine("Entra frase");
frase = Console.ReadLine();
int j = 0;
for (int i = 0; i < frase.Length; i++)
{
if (frase[i] != ' ')
{
palabra1 += frase[i];
if (pal2 == palabra1) si = true;
}
else
{
pal2 = palabra1;
palabra1 = "";
}
}
if (si == true) Console.WriteLine($" SI HAY palabras seguidamente
repetidas ");
else Console.WriteLine($"NO HAY PALABRAS REPETIDAS AQUI");
If you can't use any functions(split, regex, indexOf, etc), then what you should do is loop through each character of the text, and push the currently processed segment into your word list when you reach a (white)space.
String testString = "This is a test string ";
ArrayList words = new ArrayList();
string currentWord = "";
foreach(char c in testString)
{
if(Char.IsWhiteSpace(c))
{
if(currentWord.Length > 0)
{
words.Add(currentWord);
currentWord = "";
}
}
else
{
currentWord+=c;
}
}

find and extract a number from a string C# [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have a requirement to find and extract a number contained within a string.
For example, from these strings:
"O:2275000 BF:3060000 D:3260000 E:3472000 I:3918000 T:4247000 UF:4777000 A:4904000 AD:5010000 X:5243000 G:21280000"
extract :
1.2275000
2.3060000
3.3260000
....
It would be :
string temp = yourText;
List<int> numbers = new List<int>();
Regex re = new Regex(#"\d+");
Match m = re.Match(temp);
while (m.Success)
{
numbers.Add(Convert.ToInt32(m.Value));
temp = temp.Substring(m.Index + m.Length);
m = re.Match(temp);
}
First of all, you mentioned "from these strings", though you gave a single string. I am not clear about this part.
Secondly, what do you mean by extract? Do you want to find the position of a number in the string? If yes then you can simply use string search as following
string str = "O:2275000 BF:3060000 D:3260000";
int index = str.IndexOf("3060000");
if (index != -1)
{
Console.WriteLine(index);
}
else
{
Console.WriteLine("Not Found");
}
Or if the problem is stated like that: you were given a string and you want to extract the numbers out of it, then you can do it like so:
List<decimal> findNumbers(string str)
{
List<decimal> x = new List<decimal>();
string tokens = "";
foreach (char ch in str)
{
if (Char.IsNumber(ch))
{
tokens = tokens + ch;
}
if (!Char.IsNumber(ch) && !String.IsNullOrEmpty(tokens))
{
decimal num = Convert.ToDecimal(tokens);
x.Add(Convert.ToDecimal(num));
tokens = "";
}
}
if (String.IsNullOrEmpty(tokens))
{
x.Add(Convert.ToDecimal(tokens));
}
return x;
}
this function returns the list of numbers available in the string.
We can try using string split here:
string input = "O:2275000 BF:3060000 D:3260000";
string[] parts = input.Split(' ');
string[] numbers = parts
.Select(s => s.Split(':')[1])
.ToArray();
foreach (string n in numbers)
{
Console.WriteLine(n);
}
This prints:
2275000
3060000
3260000
You can do this in a single line with Linq.
string numbers = "O:2275000 BF:3060000 D:3260000 E:3472000 I:3918000 T:4247000 UF:4777000 A:4904000 AD:5010000 X:5243000 G:21280000";
List<int> list = numbers.Split(' ').Select(x => Convert.ToInt32(string.Concat(x.Where(Char.IsDigit)))).ToList();
Tim Biegeleisen's answer is correct except it does not produce floating point output as you mentioned in your question. In his answere, just replace foreach loop with for statement, like this:
string input = "O:2275000 BF:3060000 D:3260000";
string[] parts = input.Split(' ');
string[] numbers = parts
.Select(s => s.Split(':')[1])
.ToArray();
for(int i = 0; i < numbers.Length; i++)
{
Console.WriteLine("{0}.{1}", i+1, numbers[i]);
}

How to replace a particular character from string in c#?

I have a string like AX_1234X_12345_X_CXY, I want to remove X from after the first underscore _ i.e. from 1234X to 1234. So final output will be like AX_1234_12345_X_CXY. How to do it?? If I use .Replace("X", "") it will replace all X which I don't want
You can iterate trough the string from the first occurrence of '_' .
you can find the first occurrence of '_' using IndexOf().
when loop will get to 'X' it will not append it to the "fixed string".
private static void Func()
{
string Original = "AX_1234X_12345_X_CXY";
string Fixed = Original.Substring(0, Original.IndexOf("_", 0));
// in case you want to remove all 'X`s' after first occurrence of `'_'`
// just dont use that variable
bool found = false;
for (int i = Original.IndexOf("_", 0); i < Original.Length; i++)
{
if (Original[i].ToString()=="X" && found == false)
{
found = true;
}
else
{
Fixed += Original[i];
}
}
Console.WriteLine(Fixed);
Console.ReadLine();
}
Why not good old IndexOf and Substring?
string s = "AX_1234X_12345_X_CXY";
int pUnder = s.IndexOf('_');
if (pUnder >= 0) { // we have underscope...
int pX = s.IndexOf('X', pUnder + 1); // we should search for X after the underscope
if (pX >= 0) // ...as well as X after the underscope
s = s.Substring(0, pX) + s.Substring(pX + 1);
}
Console.Write(s);
Outcome:
AX_1234_12345_X_CXY
string original = #"AX_1234X_12345_X_CXY";
original = #"AX_1234_12345_X_CXY";
One way is String.Remove, because you can tell exactly where to remove from. If the offending "X" is always in the same place, you can use:
string newString = old.Remove(7,1);
This will remove 1 character starting as position 7 (counting from zero as the beginning of the string).
If not always in the same character position, you might try:
int xPos = old.IndexOf("X");
string newString = old.Remove(xPos,1);
EDIT:
Based on OP comment, the "X" we're targeting occurs just after the first underscore character, so let's index off of the first underscore:
int iPosUnderscore = old.IndexOf("_");
string newString = old.Remove(iPosUnderscore + 1 ,1); // start after the underscore
Try looking at string.IndexOf or string.IndexOfAny
string s = "AX_1234X_12345_X_CXY";
string ns = HappyChap(s);
public string HappyChap(string value)
{
int start = value.IndexOf("X_");
int next = start;
next = value.IndexOf("X_", start + 1);
if (next > 0)
{
value = value.Remove(next, 1);
}
return value;
}
If and only if this is always the format then it should be a simple matter of combining substrings of the original text without including the x in that position. But the op hasn't stated that this is always the case. So if this is always the format and the same character position is always removed then you could simply just
string s = "AX_1234X_12345_X_CXY";
string newstring = s.Substring(0, 7) + s.Substring(8);
OK, based on only the second set of numbers being variable in length, you could then do something like:
int startpos = s.IndexOf('_', 4);
string newstring = s.Substring(0, startpos - 1) + s.Substring(startpos);
with this code, the following tests resulted in:
"AX_1234X_12345_X_CXY" became "AX_1234_12345_X_CXY"
"AX_123X_12345_X_CXY" became "AX_123_12345_X_CXY"
"AX_234X_12345_X_CXY" became "AX_234_12345_X_CXY"
"AX_1X_12345_X_CXY" became "AX_1_12345_X_CXY"
Something like this could work. I'm sure there's a more elegant solution.
string input1 = "AX_1234X_12345_X_CXY";
string pattern1 = "^[A-Z]{1,2}_[0-9]{1,4}(X)";
string newInput = string.Empty;
Match match = Regex.Match(input1, pattern1);
if(match.Success){
newInput = input1.Remove(match.Groups[1].Index, 1);
}
Console.WriteLine(newInput);

How to read specific values in string?

For example, TOMILA RELEASE V6.24 , i want to get 6.24 i used
if (txt.Contains("<TOMILA RELEASE"))
{
int iStartIndex = txt.LastIndexOf("<TOMILA RELEASE") + 17;
for (int i = 0; i < 50; i++) {
if (txt[iStartIndex + i] == '>') break;
currentRelease += txt[iStartIndex + i];
}
}
So, my question is if i want to get the specific 6 from TOMILA RELEASE V6.24, how could i get it?
You can try LastIndexOf followed by Substring
var result = str.Substring(str.LastIndexOf('TOMILA RELEASE V') + 1);
If you want to take first number in the string you can use following regular expression.
string s = "TOMILA RELEASE V6.24";
string digit = Regex.Match(s, "\\d").Value;
Here \d is for matching the digit, you can find more about regular expression in this tutorial, The 30 Minute Regex Tutorial
If you want to extract all number before dot then you can add + with \d and use do to end the extraction.
string number = Regex.Match(s, "\\d+.").Value.Replace(".","");
If you want to get a specific portion of a string, you could use the below code
string str = "6.24";
var val = str.Substring(0, 1);

Categories

Resources