C,计算空白空间的数量

时间:2017-10-14 15:33:01

标签: c

我正在编写一个将空格替换为' - '(< - 此字符)的函数。 我最终想要回复我做了多少改变。

#include <stdio.h>
int replace(char c[])
{
    int i, cnt;
    cnt = 0;
    for (i = 0; c[i] != EOF; i++)
        if (c[i]==' ' || c[i] == '\t' || c[i] == '\n')
        {
            c[i] = '-';
            ++cnt;
        }
    return cnt;
}

main()
{
    char cat[] = "The cat sat";
    int n = replace(cat);
    printf("%d\n", n);
}

问题是,它正确地将字符串更改为“The-cat-sat”但是对于n,它返回值3,当它应该返回2时。 我做错了什么?

4 个答案:

答案 0 :(得分:1)

@ 4386427建议这应该是另一个答案。 @wildplasser已经提供了解决方案,这个答案解释了EOF和import UIKit import Parse import Alamofire import SwiftyJSON class VCreservacion: UIViewController,UITextFieldDelegate,UIScrollViewDelegate { var SUCURSALID = 0 var EMP_NOMBRE = "" var DIRECCION = "" var PROVINCIA = "" var RESTID = 20556 @IBOutlet var lbl_empresa: UILabel! @IBOutlet var lbl_direccion: UILabel! @IBOutlet var lbl_step: UILabel! @IBOutlet var cantidadView: UIView! @IBOutlet var datePicker: UIDatePicker! @IBOutlet var btn_reservar: UIButton! @IBOutlet var stackView: UIStackView! @IBOutlet var scrollView: UIScrollView! @IBOutlet var txtComentario: UITextField! @IBOutlet weak var txtCelular: UITextField! var activeField: UITextField? var steps = 2 // MARK: RESERVE ACTION @IBAction func ReserveAction(_ sender: UIButton) { print("Reservando...") // For date formater var dateformated = "" var dateformated2 = "" let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" //formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0) as TimeZone! dateformated = formatter.string(from: datePicker.clampedDate) dateformated2 = formatter.string(from: datePicker.date) print(dateformated) print(dateformated2) let cart = Cart.sharedInstance guard let user = PFUser.current() else { cart.showAlertView("Login", message: "Debes estar logeado para poder reservar.") return } Alamofire.request("URL String", parameters: ["qty": "\(steps)","sucursalid":"\(self.SUCURSALID)","restid":"\(RESTID)","comment":"\(txtComentario.text!)","phone":"\(txtCelular.text!)","datetime":"\(dateformated)","action":"request","userid":"\(user.objectId!)"]).authenticate(usingCredential: cart.credential).responseJSON() { response in if (response.error != nil ) { print(response.error.debugDescription) print(response.request) cart.showAlertView("Error", message: "there was an error.") } if(response.result.value != nil) { let json = JSON(response.result.value!); print(json); let success:Bool = json["success"].boolValue let error: Bool = json["error"].boolValue if(success) { print("con exito") let alert = UIAlertController(title: "Reserva Enviada", message: "Tu reserva ha sido enviada y será revisada por el establecimiento", preferredStyle: .alert) let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { UIAlertAction in // Get the previous Controller. let targetController: UIViewController = (self.navigationController?.viewControllers[self.navigationController!.viewControllers.count - 3])! // And go to that Controller self.navigationController?.popToViewController(targetController, animated: true) } alert.addAction(okAction) self.present(alert,animated:true) } } } } @IBAction func stepperValue(_ sender: UIStepper) { self.lbl_step.text = Int(sender.value).description steps = Int(sender.value) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) registerForKeyboardNotifications() self.scrollView.delegate = self } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) deregisterFromKeyboardNotifications() self.scrollView.delegate = nil } // MARK: Viewdidload override func viewDidLoad() { super.viewDidLoad() // enable scroll on scrollview self.scrollView.isScrollEnabled = true // step label initial value 2 self.lbl_step.text = "2" // Get celular or phone if ( Cart.sharedInstance.User_celular != "") { txtCelular.text = Cart.sharedInstance.User_celular } else { txtCelular.text = Cart.sharedInstance.User_phone } let nearesthour = Date().nearestHour() self.datePicker.minimumDate = nearesthour self.txtComentario.delegate = self self.txtCelular.delegate = self self.txtCelular.tag = 20 self.scrollView.delegate = self // tap gesture recognizer let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:))) self.scrollView.addGestureRecognizer(tap) print("el enarest hour es \(nearesthour as Date?) y el date normal es \(Date())") self.btn_reservar.layer.cornerRadius = 10 self.cantidadView.layer.cornerRadius = 10 self.lbl_empresa.text = EMP_NOMBRE self.lbl_direccion.text = DIRECCION /* print("VC Reservacion") print("SUCURSAL \(SUCURSALID) ") print("EMP NOMBRE " + EMP_NOMBRE) print("DIRECCION " + DIRECCION) */ } // MARK: TEXTFIELD STUFF func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { self.activeField = textField return true } /* func textFieldDidBeginEditing(_ textField: UITextField) { self.activeField = textField } */ func textFieldDidEndEditing(_ textField: UITextField) { activeField = nil } func registerForKeyboardNotifications(){ //Adding notifies on keyboard appearing NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil) } func deregisterFromKeyboardNotifications(){ //Removing notifies on keyboard appearing NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil) } @objc func keyboardWasShown(notification: NSNotification){ //Need to calculate keyboard exact size due to Apple suggestions print(" Keyboaard shown") var info = notification.userInfo! let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size print(" el keyboardsize is \(keyboardSize)") let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize!.height + 80, 0.0) self.scrollView.contentInset = contentInsets self.scrollView.scrollIndicatorInsets = contentInsets var aRect : CGRect = self.view.frame print("VIEW COMPLETE FRAME IS \(aRect)") print("KEYBOARD FRAME HEIGHT \(keyboardSize!.height)") aRect.size.height -= keyboardSize!.height print("FRAME MENOS KEYBOARD ES \(aRect)") print("SCROLLVIEW CONTENT \(self.scrollView.contentSize)") if let activeField = self.activeField { print("ACTIVEFIELD FRAME ORIGIN \(activeField.frame.origin) ") print("Active field is textfield tag is \(activeField.tag)") // if (!aRect.contains(activeField.frame.origin)){ print("arect Does Not contains activeField") self.scrollView.scrollRectToVisible(activeField.frame, animated: true) print("TEXTFIELD FRAME ES \(activeField.frame)") print(" SCROLLVIEW CONTENT \(self.scrollView.contentSize)") //} } } @objc func keyboardWillBeHidden(notification: NSNotification){ //Once keyboard disappears, restore original positions var info = notification.userInfo! let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, -keyboardSize!.height, 0.0) self.scrollView.contentInset = contentInsets self.scrollView.scrollIndicatorInsets = contentInsets self.activeField = nil self.view.endEditing(true) self.scrollView.isScrollEnabled = false } @objc func handleTap(_ sender: UITapGestureRecognizer) { self.view.endEditing(true) print("Tap") } func textFieldShouldReturn(_ textField: UITextField) -> Bool { self.view.endEditing(true) return false } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() scrollView.contentSize = CGSize(width: view.frame.width, height: view.frame.height) print(" SCROLLVIEW CONTENT AFTER SUBVIEWS \(self.scrollView.contentSize)") } /* // NOT WORKING BECAUSE OF UISCROLLVIEW IN PLACE, MUST USE UITAPGESTURE RECOGNIZER override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.view.endEditing(true) self.activeField?.resignFirstResponder() } */ }

只有在从文件中读取时才会使用'\0'(EOF - &gt;文档结束)。请参阅this讨论。 EOF用于表示文件结尾,其值取决于系统。事实上,EOF是一种条件,而不是一种价值。你可以找到很好的解释in this thread。当使用char数组或char指针时,它将始终由EOF字符终止,并且总是只有其中一个,因此,当迭代数组时,您将使用它来突破循环/指针。这是确保您不会访问未分配的内存的可靠方法。

答案 1 :(得分:0)

  • 字符串以0(零)值结束,而不是EOF(因此:问题中的程序将扫描字符串超出终端{{1直到碰巧在某处发现\0;但你已经在UB的土地上了,这里)
  • [sylistic]函数参数可以是一个字符指针(C中不能存在数组参数)
  • [stylistic]指针版本不需要&#39; i&#39;变量
  • [stylistic]计数永远不会是负数:直观地说,无符号计数器是首选。 (它甚至可以是-1,就像其他字符串函数一样)
  • [styleistic] size_t可以避开(IMO)丑陋switch(){}列表,添加案例也更容易。
||

答案 2 :(得分:0)

在for循环结束条件中使用的

EOF是你不使用的问题是检查文件/流的结尾。

for (i = 0; c[i] != EOF; i++)

EOF本身不是一个字符,而是一个信号,表示流中没有更多可用的字符。

如果您要检查行尾,请使用

for (i = 0; c[i] != "\0"; i++)

答案 3 :(得分:0)

#include <stdio.h>

int repl(int c);

int main(void){
    int c, nc;
    nc =0;

    while ((c=getchar())!=EOF)
        nc = replc(c);

    printf("replaced: %d times\n", nc);

    return 0;
}

int replc(int c){
    int nc = 0;
    for(; (c = getchar())!=EOF; ++c)
       if (c == ' '){
          putchar('-');
          ++nc;
       } else putchar(c);
    return nc;
}