C# How to replace spaces with new lines [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
How to replace spaces with new lines. My text file looks like:
1 2 3 4 5 6
but I want to myString look like:
1
2
3
4
Code:
StreamReader myReader = new StreamReader("TextFile1.txt");
string myString = myReader.ReadLine();
myString = myString.Replace(' ', '\n');
at current state it is only adding \n over spaces.

Use:
myString = String.Join(Environment.NewLine,
myString.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries));
This will split the string based on space and then join them using Environment.NewLine. So in case of multiple spaces only one new line will appear.

You can use Environment.NewLine:
myString = myString.Replace(' ', Environment.NewLine);
This is a platform-independent line-replace. Don't use '\n'.
Environment.NewLine basically outputs "\r\n" for non-Unix platforms, and "\n" for Unix platforms. You are not on a Unix platform, so it is not outputting correctly.
You will run into a lot of weird problems if you use \n, and/or \r\n\ in the future. It's best to just use Environment.NewLine. This works on MessageBox.Show() dialogs, in StreamWriter, StreamReader, etc.
You can port the code anywhere, whereas if you were to use \n or \r\n, you'd be restricted to the platform which supports it.

Use regular expressions to replace each spaces with new lines.
using System;
using System.Text.RegularExpressions;
public class Program {
public static void Main() {
var input = "1 2 3 4 5 6";
Console.WriteLine("input:");
Console.WriteLine(input);
var output = Regex.Replace(input, " ", "\n");
Console.WriteLine("output:");
Console.WriteLine(output);
}
}
https://dotnetfiddle.net/F6vmj4

Related

How do I remove an X number of capital letters from a string? [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 4 years ago.
Improve this question
I want to remove an X number of capital letters from a string.
For example if I had the strings:
string Line1 = "NICEWEather";
and
string Line2 = "HAPpyhour";
How would I create a function that pulls out the 2 sets of Capital letters?
Try using regular expressions with \p{Lu} for a Unicode capital letter
using System.Text.RegularExpressions;
...
// Let's remove 2 or more consequent capital letters
int X = 2;
// English and Russian
string source = "NICEWEather - ХОРОшая ПОГОда - Keep It (HAPpyhour)";
// ather - шая да - Keep It (pyhour)
string result = Regex.Replace(source, #"\p{Lu}{" + X.ToString() + ",}", "");
Here we use \p{Lu}{2,} pattern: capital letter appeared X (2 in the code above) or more times.
To remove capital letter from string
string str = " NICEWEather";
Regex pattern = new Regex("[^a-z]");
string result = pattern.Replace(str, "");
Console.WriteLine(result );
output: ather
to remove capital letter if occurrences more than once in sequence order then try this
string str = " NICEWEather";
Regex pattern = new Regex(#"\p{Lu}{2,}");
string output = pattern.Replace(str, "");
Console.WriteLine(output);

Regexp - Delete the one word before XXX, remove XXX too [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I need to remove a word XXX in a string and also one word before XXX.
How I can do that with C# Regexp?
Do a single regex replacement:
string input = #"Hello World XXX Goodbye XXX Rabbit!";
Regex rgx = new Regex(#"\s*\w+\s+(?:XXX|xxx)"); // or maybe [Xx]{3}
string result = rgx.Replace(input, "", 1);
Console.WriteLine(result);
Hello Goodbye XXX Rabbit!
Demo
This replacement only would target XXX for removal if it be preceded by a word (one character or more). Explore the demo to see how it would behave with various inputs.
We can also make the search pattern case insensitive via this:
Regex rgx = new Regex(#"\s*\w+\s+XXX", RegexOptions.IgnoreCase);
^^^^^ add this
U can use the replace method :
String s = "aaa bbb";
s = s.Replace("a", "")
// The example displays the following output:
// The initial string: 'aaa bbb'
// The final string: 'bbb'
Or use a Regex in replace :
tmp = s.Replace(n, "[^0-9a-zA-Z]+", "");

How can I return the index of the second word in a string that can have multiple white spaces followed by one word followed by multiple white spaces? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
String str =" vol ABCD C XYZ";
I want to return the index of "A"
Note: There are multiple white spaces before all words including the first.
This will get the index of A in your original example (String str =" vol ABCD C XYZ";):
int indexOfABCD = str.IndexOf(str.Trim()[str.Trim().IndexOf(' ')+1]);
If you have something like String str = " vol ABCD C XYZ"; where there are multiple spaces:
string secondword = str.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries)[1];
int indexOfAinABCD = str.IndexOf(secondword.First());
If you want to get the indices of all the letters in the second word:
IEnumerable<int> fullindex = Enumerable.Range(indexOfAinABCD, secondword.Length);
EDIT:
This will fail if you have A anywhere else in the first word. You should get an exact match through Regex:
int indexOfAinABCD = Regex.Match(str, string.Format(#"\W{0}\W",secondword)).Index+1;
IEnumerable<int> fullindex = Enumerable.Range(indexOfAinABCD, secondword.Length);
So something like String str = " vABCDol ABCD C XYZ"; won't be an issue

Match and replace only line breaks in string [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to replace line break in string with blank.if string has only line break it should be replace with blank string if string has text along with line breaks it should not be replace with anything.
string test1 = "\r\n\r\n\r\n\r\n\r\n\r\n\r\nTestcompanyAC\r\nRegistration Number: 19871\r\n\r\n\r\nSTATEMENTS\r\n\r\nYear ended 31 December 2013\r\n\r\n"
string test2 = "\r\n\r\n\r\n\r\n\r\n\r\n\r\n"
output: test1 as it is and test2=""
Thanks
string test2 = "\r\n\r\n\r\n\r\n\r\n\r\n\r\n";
if (test2.All(c => c == '\n' || c == '\r'))
test2 = "";
You can use the ^ and $ delimiters to match beginning and ending.
Regex.Replace(test2, #"^[\r\n]*$", String.Empty)
Why would you bother with Regex.
This does what you need:
if (string.IsNullOrWhitespace(string_variable_here))
string_variable_here = "";
If you're just looking for a blank entry.. the above is all you need.
Just a guess, and a somewhat different attempt, but are you looking for a way to trim your string, to remove leading and ending whitespaces?
str = str.Trim();
That should give you
test1 = "TestcompanyAC\r\nRegistration Number: 19871\r\n\r\n\r\nSTATEMENTS\r\n\r\nYear ended 31 December 2013"
test2 = ""

How to remove extra hyphens from string in c#? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a string in which spaces are replaced by hyphen i.e '-' if there multiple hyphens then I want to remove all but one from the string. Only hyphens must be removed; not numbers that are consecutive.
Eg: --11- must be -11- and not -1-
Eg: --12- o/p: -12-
Eg: -12-- o/p: -12-
using Linq or a string function in C#.
I have tried it using str = str.Remove(str.Length - 1);, but it only removes one character.
If you just want to collapse multiple consecutive - characters into one, you could easily do this using regex:
string output = Regex.Replace(input, #"\-+", "-");
try
string sample = "--12";
string Reqdoutput = sample.Replace("--", "-");
If you want to replace just the hyphen, you can do one of the things given in the other answers. For removing all double characters, you can do this:
String input = "------hello-----";
int i = 1;
while (i < input.Length)
{
if (input[i] == input[i - 1])
{
input = input.Remove(i, 1);
}
else
{
i++;
}
}
Console.WriteLine(input); // Will give "-helo-"
Why not just do :
yourString = yourString.Replace("--", "-");
Or did I understand the problem wrong ?

Categories