logo

Odstráňte ďalšie priestory zo strunu

Vzhľadom na reťazec obsahujúci mnoho po sebe idúcich priestorov orežte všetky medzery tak, aby všetky slová mali obsahovať Iba jediný priestor medzi nimi. Konverzia by sa mala vykonať na mieste a riešenie by malo zvládnuť koncové a vedúce priestory a tiež odstrániť predchádzajúce priestory pred bežnou interpunkciou, ako je čiarka s plnou bránou a otáznik.

Príklady: 



    Input:      
str = ' Hello Geeks . Welcome to GeeksforGeeks . ';
Output:
'Hello Geeks. Welcome to GeeksforGeeks.'
Input:
str = 'GeeksforGeeks';
Output:
'GeeksforGeeks'
(No change is needed)


Tento problém je rozšírením Odstráňte medzery z daného reťazca

Metóda 1:

haldy triediť
  • Cieľom je udržiavať 2 ukazovatele. Spočiatku poukazujú na začiatok poľa.
  • Prvý ukazovateľ sleduje ďalšiu pozíciu, ktorá sa má vyplniť výstupným reťazcom.
  • Druhý ukazovateľ je pokročilý, aby si prečítal všetky znaky reťazca jeden po druhom.
  • Po nájdení akéhokoľvek znaku, ktorý nie je priestorom, je znak skopírovaný do umiestnenia prvého ukazovateľa a potom sú pokročilé prvé a druhé ukazovatele.
  • Ak je znak, ktorý nie je priestorom, čiarkou na úplné zastavenie alebo otáznik, odstránime tiež predchádzajúci priestor pred ním.
  • Pri nájdení po sebe idúcich priestorových znakov sa skopíruje jediný priestor na umiestnenie prvého ukazovateľa a zvyšok sa ignoruje. V roztoku sa riešia vedúce a koncové priestory.


Nižšie je uvedená implementácia vyššie uvedenej myšlienky C ++.



C++
// C++ program to implement custom trim() function #include    using namespace std; // Function to in-place trim all spaces in the // string such that all words should contain only // a single space between them. void removeSpaces(string &str) {  // n is length of the original string  int n = str.length();  // i points to next position to be filled in  // output string/ j points to next character  // in the original string  int i = 0 j = -1;  // flag that sets to true is space is found  bool spaceFound = false;  // Handles leading spaces  while (++j < n && str[j] == ' ');  // read all characters of original string  while (j < n)  {  // if current characters is non-space  if (str[j] != ' ')  {  // remove preceding spaces before dot  // comma & question mark  if ((str[j] == '.' || str[j] == '' ||  str[j] == '?') && i - 1 >= 0 &&  str[i - 1] == ' ')  str[i - 1] = str[j++];  else  // copy current character at index i  // and increment both i and j  str[i++] = str[j++];  // set space flag to false when any  // non-space character is found  spaceFound = false;  }  // if current character is a space  else if (str[j++] == ' ')  {  // If space is encountered for the first  // time after a word put one space in the  // output and set space flag to true  if (!spaceFound)  {  str[i++] = ' ';  spaceFound = true;  }  }  }  // Remove trailing spaces  if (i <= 1)  str.erase(str.begin() + i str.end());  else  str.erase(str.begin() + i - 1 str.end()); } // Driver Code int main() {  string str = ' Hello Geeks . Welcome to'  ' GeeksforGeeks . ';  removeSpaces(str);  cout << str;  return 0; } 
Java
class Main{  public static String removeSpaces(String s) {  int n = s.length();  int i = 0 j = -1;  boolean spaceFound = false;    // Handles leading spaces  while (j < n - 1 && s.charAt(j + 1) == ' ') {  j++;  }    // read all characters of original string  while (j < n) {  // if current characters is non-space  if (s.charAt(j) != ' ') {  // remove preceding spaces before dot  // comma & question mark  if ((s.charAt(j) == '.' || s.charAt(j) == '' ||  s.charAt(j) == '?') && i - 1 >= 0 &&   s.charAt(i - 1) == ' ') {  s = s.substring(0 i - 1) + s.charAt(j) + s.substring(i);  j++;  } else {  // copy current character at index i  // and increment both i and j  s = s.substring(0 i) + s.charAt(j) + s.substring(i + 1);  i++;  j++;  }    // set space flag to false when any  // non-space character is found  spaceFound = false;  } else if (s.charAt(j) == ' ') {  // If space is encountered for the first  // time after a word put one space in the  // output and set space flag to true  if (!spaceFound) {  s = s.substring(0 i) + ' ' + s.substring(i + 1);  i++;  spaceFound = true;  }  j++;  }  }    // Remove trailing spaces  if (i <= 1) {  s = s.substring(0 i);  } else {  s = s.substring(0 i - 1);  }  return s; } // Driver code public static void main(String[] args) {  String str = ' Hello Geeks . Welcome to'   + ' GeeksforGeeks . ';  str = removeSpaces(str);  System.out.println(str); }   } 
Python3
# Python code for the above approach def removeSpaces(s): # n is length of the original string n = len(s) # i points to next position to be filled in # output string/ j points to next character # in the original string i = 0 j = -1 # flag that sets to true is space is found spaceFound = False # Handles leading spaces while j < n - 1 and s[j + 1] == ' ': j += 1 # read all characters of original string while j < n: # if current characters is non-space if s[j] != ' ': # remove preceding spaces before dot # comma & question mark if ((s[j] == '.' or s[j] == '' or s[j] == '?') and i - 1 >= 0 and s[i - 1] == ' '): s = s[:i - 1] + s[j] + s[i:] j += 1 else: # copy current character at index i # and increment both i and j s = s[:i] + s[j] + s[i + 1:] i += 1 j += 1 # set space flag to false when any # non-space character is found spaceFound = False # if current character is a space elif s[j] == ' ': # If space is encountered for the first # time after a word put one space in the # output and set space flag to true if not spaceFound: s = s[:i] + ' ' + s[i + 1:] i += 1 spaceFound = True j += 1 # Remove trailing spaces if i <= 1: s = s[:i] else: s = s[:i - 1] return s # Driver Code str = ' Hello Geeks . Welcome to'  ' GeeksforGeeks . ' str = removeSpaces(str) print(str) # This code is contributed by adityasharmadev01 
C#
// C# program to implement custom trim() function using System; public class Gfg {  public static void Main()  {  string str = ' Hello Geeks . Welcome to' +  ' GeeksforGeeks . ';  removeSpaces(ref str);  Console.WriteLine(str);  }  // Function to in-place trim all spaces in the  // string such that all words should contain only  // a single space between them.  public static void removeSpaces(ref string str)  {  // n is length of the original string  int n = str.Length;  // i points to next position to be filled in  // output string/ j points to next character  // in the original string  int i = 0 j = -1;  // flag that sets to true is space is found  bool spaceFound = false;  // Handles leading spaces  while (++j < n && str[j] == ' ');  // read all characters of original string  while (j < n)  {  // if current characters is non-space  if (str[j] != ' ')  {  // remove preceding spaces before dot  // comma & question mark  if ((str[j] == '.' || str[j] == '' ||  str[j] == '?') && i - 1 >= 0 &&  str[i - 1] == ' ')  str = str.Remove(i - 1 1).Insert(i - 1 str[j++].ToString());  else  {  // copy current character at index i  // and increment both i and j  str = str.Remove(i 1).Insert(i str[j++].ToString());  i++;  }  // set space flag to false when any  // non-space character is found  spaceFound = false;  }  // if current character is a space  else if (str[j++] == ' ')  {  // If space is encountered for the first  // time after a word put one space in the  // output and set space flag to true  if (!spaceFound)  {  str = str.Remove(i 0).Insert(i ' ');  i++;  spaceFound = true;  }  }  }  // Remove trailing spaces  if (i <= 1)  str = str.Remove(i n - i);  else  str = str.Remove(i - 1 n - i + 1);  } } 
JavaScript
// JavaScript program to implement custom trim() function // Function to in-place trim all spaces in the // string such that all words should contain only // a single space between them. function removeSpaces(str) {  // n is length of the original string  let n = str.length;    // i points to next position to be filled in  // output string/ j points to next character  // in the original string  let i = 0 j = -1;    // flag that sets to true is space is found  let spaceFound = false;    // Handles leading spaces  while (++j < n && str[j] == ' ');    // read all characters of original string  while (j < n) {  // if current characters is non-space  if (str[j] != ' ') {  // remove preceding spaces before dot  // comma & question mark  if ((str[j] == '.' || str[j] == '' ||  str[j] == '?') && i - 1 >= 0 &&  str[i - 1] == ' ')  str = str.substr(0 i - 1) + str[j++] + str.substr(i);    else  // copy current character at index i  // and increment both i and j  str = str.substr(0 i++) + str[j++] + str.substr(i);    // set space flag to false when any  // non-space character is found  spaceFound = false;  }  // if current character is a space  else if (str[j++] == ' ') {  // If space is encountered for the first  // time after a word put one space in the  // output and set space flag to true  if (!spaceFound) {  str = str.substr(0 i++) + ' ' + str.substr(i);  spaceFound = true;  }  }  }    // Remove trailing spaces  if (i <= 1)  str = str.substr(0 i);  else  str = str.substr(0 i - 1);    return str; } // Driver Code let str = ' Hello Geeks . Welcome to' + ' GeeksforGeeks . '; str = removeSpaces(str); console.log(str); 

Výstup:  

Hello Geeks. Welcome to GeeksforGeeks.  


Zložitosť vyššie uvedeného roztoku je O (n).
Pomocný priestor je o (1), pretože konverzia sa vykonáva na mieste.

Metóda 2:
Ďalšie riešenie využívajúce preddefinované funkcie v Pythone 3: 



C++
#include    #include  int main() {  std::string input_string = ' Hello Geeks . Welcome  Do you love Geeks  Geeks ? ';  std::string output_string;  bool space_flag = false; // Flag to check if spaces have occurred  for (size_t index = 0; index < input_string.length(); ++index) {  if (input_string[index] != ' ') {  if (space_flag) {  if (input_string[index] == '.' || input_string[index] == '?' || input_string[index] == '') {  // Do nothing  } else {  output_string += ' ';  }  space_flag = false;  }  output_string += input_string[index];  } else if (index > 0 && input_string[index - 1] != ' ') {  space_flag = true;  }  }  std::cout << output_string << std::endl;  return 0; } 
Java
public class Main {  public static void main(String[] args) {  String inputString = ' Hello Geeks . Welcome  Do you love Geeks  Geeks ? ';  String outputString = '';  boolean spaceFlag = false; // Flag to check if spaces have occurred  for (int index = 0; index < inputString.length(); ++index) {  if (inputString.charAt(index) != ' ') {  if (spaceFlag) {  if (inputString.charAt(index) == '.' || inputString.charAt(index) == '?' || inputString.charAt(index) == '') {  // Do nothing  } else {  outputString += ' ';  }  spaceFlag = false;  }  outputString += inputString.charAt(index);  } else if (index > 0 && inputString.charAt(index - 1) != ' ') {  spaceFlag = true;  }  }  System.out.println(outputString);  } } 
Python3
# Python program to Remove  # extra spaces from a string input_string =  ' Hello Geeks . Welcome  Do you love Geeks  Geeks ? ' output_string = [] space_flag = False # Flag to check if spaces have occurred for index in range(len(input_string)): if input_string[index] != ' ': if space_flag == True: if (input_string[index] == '.' or input_string[index] == '?' or input_string[index] == ''): pass else: output_string.append(' ') space_flag = False output_string.append(input_string[index]) elif input_string[index - 1] != ' ': space_flag = True print (''.join(output_string)) 
C#
using System; class Program {  static void Main()  {  string inputString = ' Hello Geeks . Welcome to GeeksforGeeks  Do you love Geeks  Geeks ? ';  char[] outputArray = new char[inputString.Length]; // Using char array for efficient string building  int outputIndex = 0;  bool spaceFlag = false; // Flag to check if spaces have occurred  for (int index = 0; index < inputString.Length; ++index)  {  if (inputString[index] != ' ')  {  if (spaceFlag)  {  // Check if the current character is a punctuation mark  if (inputString[index] == '.' || inputString[index] == '?' || inputString[index] == '')  {  // Do nothing  }  else  {  outputArray[outputIndex++] = ' ';  }  spaceFlag = false;  }  outputArray[outputIndex++] = inputString[index];  }  else if (index > 0 && inputString[index - 1] != ' ')  {  spaceFlag = true;  }  }  string outputString = new string(outputArray 0 outputIndex); // Convert char array to string  Console.WriteLine(outputString);  } } 
JavaScript
let inputString = ' Hello Geeks . Welcome  Do you love Geeks  Geeks ? '; let outputString = ''; let spaceFlag = false; // Flag to check if spaces have occurred for (let index = 0; index < inputString.length; ++index) {  if (inputString[index] !== ' ') {  if (spaceFlag) {  if (inputString[index] === '.' || inputString[index] === '?' || inputString[index] === '') {  // Do nothing  } else {  outputString += ' ';  }  spaceFlag = false;  }  outputString += inputString[index];  } else if (index > 0 && inputString[index - 1] !== ' ') {  spaceFlag = true;  } } console.log(outputString); 

Výstup:   

Hello Geeks. Welcome to GeeksforGeeks. Do you love Geeks Geeks?  

Zložitosť vyššie uvedeného roztoku je O (n). 
Pomocný priestor je o (n), pretože sa musel vytvoriť ďalší zoznam. 

in.next java

Metóda 3: (Pomocou vstavanej funkcie)

C++
#include    #include  #include  int main() {  std::string str = ' Hello Geeks . Welcome  Do you love Geeks  Geeks ? ';    // Use regular expression to replace multiple spaces with a single space  std::regex pattern('\s+');  std::string result = std::regex_replace(str pattern ' ');    // Remove leading and trailing spaces  size_t firstNonSpace = result.find_first_not_of(' ');  size_t lastNonSpace = result.find_last_not_of(' ');    if (firstNonSpace != std::string::npos && lastNonSpace != std::string::npos) {  result = result.substr(firstNonSpace lastNonSpace - firstNonSpace + 1);  }    std::cout << result << std::endl;    return 0; } // code contributed by shinjanpatra 
Java
/** Java Program to remove extra spaces from a string **/ public class GFG {  public static void main(String args[]) {  String str = ' Hello Geeks . Welcome  Do you love Geeks  Geeks ? ';  System.out.println(str.replaceAll('\s+'' ').trim());  } } 
Python3
# Python program to remove extra spaces from a string # Input string str = ' Hello Geeks . Welcome  Do you love Geeks  Geeks ? ' # Removing extra spaces using regex import re str = re.sub('s+' ' ' str).strip() # Printing the final string print(str) 
C#
// C# Program to remove // extra spaces from a string using System; class Program {  static void Main(string[] args)  {  string str  = ' Hello Geeks . Welcome  Do you love Geeks  Geeks ? ';  // Removing extra spaces using regex and print  Console.WriteLine(  System.Text.RegularExpressions.Regex.Replace(  str.Trim() @'s+' ' '));  } } 
JavaScript
<script> // JavaScript Program to remove // extra spaces from a string var str = ' Hello Geeks . Welcome  Do you love Geeks  Geeks ? '; document.write(str.replace('\s+' ' ').trim()); // This code is contributed by rdtank </script> 

Výstup:  

Hello Geeks . Welcome  Do you love Geeks  Geeks ?  

Zložitosť : O (n) kde n je počet znakov v reťazci. 
Pomocný priestor: O (1) Pretože existujú iba malé písmená.


Tento článok prispieva Aarti_rathi a Aditya Goel .